4

I've configured both MEDIA_ROOT and MEDIA_URL and this works perfectly fine. My MEDIA files stored in a directory named /media/, now I want to store newly uploaded files to a new directory (for ex. /media2/) without breaking previous files.

For example I had a Book model like this:

class Book(models.Model):
    # name
    # author
    cover = models.ImageField()

Now imagine I have 500 objects of Book model, so each cover has a path and url like this:

url: http://example.com/media/books/thumb.jpg

path: /home/myproj/media/books/thumb.jpg

Now, I want to store covers for my newly created books in another directory, for ex. :

url: http://example.com/media2/books/thumb.jpg

path: /home/myproj/media2/books/thumb.jpg

without breaking previous 500 books!

How can I achieve this ?! (Django 3.1.2)

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
Omid Adib
  • 170
  • 1
  • 8

1 Answers1

1

it's important to upload all files to one directory. From there, you can define the upload_to attribute for files: "This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method."

Here are a couple of examples from Django docs:

class MyModel(models.Model):
  # file will be uploaded to MEDIA_ROOT/uploads
  upload = models.FileField(upload_to='uploads/')
  # or...
  # file will be saved to MEDIA_ROOT/uploads/2015/01/30
  upload = models.FileField(upload_to='uploads/%Y/%m/%d/')

Or create a function to pass into the model:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(models.Model):
    upload = models.FileField(upload_to=user_directory_path)
joshlsullivan
  • 1,375
  • 2
  • 14
  • 21
  • 1
    Thanks for response, but the upload_to attribute just creates a new directory in the same MEDIA_ROOT, the question I asked was about how can I have multiple MEDIA_ROOTs ! – Omid Adib May 10 '22 at 07:24
  • 2
    @OmidAdib my advice is to upload everything to one media root and then define subdirectories. Why would you upload to multiple media roots? – joshlsullivan May 10 '22 at 14:28
  • 1
    I'm using ubuntu server for production with 100GB mounted in /dev/sda1. Now it's full and I bought another volume which is mounted as /dev/sda2. That's why I want to have multiple media_roots because I can't merge these two volumes to be one! – Omid Adib May 10 '22 at 14:54