32

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.

  • More importantly, why is your deployment script overwriting uploaded content? – Dominic Rodger Nov 13 '09 at 13:06
  • It's not overwriting the uploads because I copy the dir out of the media dir first. Im trying to upload to a different directory so I can overwrite media without having to move uploads. –  Nov 13 '09 at 13:09

2 Answers2

61

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

arogachev
  • 33,150
  • 7
  • 114
  • 117
  • 1
    nice job. i just played with django filefields in an application i'm writing for work. i may end up going this route as well. – Brandon Henry Nov 13 '09 at 14:46
2

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.

Yannic Hamann
  • 4,655
  • 32
  • 50
  • If you have a different UPLOAD_ROOT on production, it could say "you have changes that are not yet reflected in a migration", what is not really a thing you'd want to see when calling `manage.py migrate` on production? – benzkji Sep 14 '22 at 13:31