Django upload_to outside of MEDIA_ROOT

Question:

My deployment script overwrites the media and source directories which means I have to move the uploads directory out of the media directory, and replace it after the upload has been extracted.

How can I instruct django to upload to /uploads/ instead of /media/?

So far I keep getting django Suspicious Operation errors! 🙁

I suppose another solution might be a symlink?

Many thanks,
Toby.

Asked By: user210437

||

Answers:

I did the following:

from django.core.files.storage import FileSystemStorage

upload_storage = FileSystemStorage(location=UPLOAD_ROOT, base_url='/uploads')

image = models.ImageField(upload_to='/images', storage=upload_storage) 

UPLOAD_ROOT is defined in my settings.py file: /foo/bar/webfolder/uploads

Answered By: user210437

While the accepted answer is probably what you want, we now have the option with django 3.1 that we can decide which storage to use at runtime by passing a function to the storage argument of an ImageField or FileField.

def select_storage():
    return MyLocalStorage() if settings.DEBUG else MyRemoteStorage()


class MyModel(models.Model):
    my_file = models.FileField(storage=select_storage)

Have a look at the official docs.

Please note that the current accepted answer writes the actual value of the variable UPLOAD_ROOT to the migration file. This doesn’t produce any SQL when you apply it to the database but may be confusing if you change that setting frequently.

Answered By: Yannic Hamann