Omid Adib
Omid Adib

Reputation: 170

Django - how to store ImageField files in different folders?

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)

Upvotes: 4

Views: 1593

Answers (1)

joshlsullivan
joshlsullivan

Reputation: 1500

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)

Upvotes: 1

Related Questions