Set an ImageField path in Django manually

Aug 23, 2012

Apparently this is a confusing topic. Let’s say you have a Django model with an ImageField and some existing media files, and you’d like to connect the files to the ImageField. This is relatively painless and doesn’t require you to use the save() method on the ImageField.

If you only want to set an ImageField to point to an existing file, assign a string containing the path relative to settings.MEDIA_ROOT to the field. E.g.:

This works as of (and possibly before) Django 1.3.

Note a couple of things:

Setting the path ignores your upload_to value. You have to prefix your string with that value yourself.

Again, you don’t have to call save() on the ImageField — just the model instance. There are some StackOverflow posts that advise going the route of calling save() on the ImageField, which requires you to open a file descriptor, etc. This isn’t necessary, will end up copying the file, and ignores any prefixed paths, resulting in a path that is always, in my testing, settings.MEDIA_ROOT/filename.jpeg.

Follow my posts