Skip to content

Django Tip: No leading slash for upload_to for FileField and ImageField

2008 May 9
tags: ,
by pk

This is a common mistake. When defining a FileField or an ImageField, you need to specify
where the files are stored. This is done by specifying a relative path in the upload_to
argument. Django will then store your files in a subdirectory as named, under the MEDIA_ROOT
directory. But, don’t put a leading slash in the relative path. Otherwise it will try to store
the file at the system root directory.

MEDIA_ROOT = ‘/home/myname/files/
upload_to=’pictures’
file: abc.jpg
results in: /home/myname/files/pictures/abc.jpg

But

MEDIA_ROOT = ‘/home/myname/files/
upload_to=’/pictures’
file: abc.jpg
results in: /pictures/abc.jpg

Also a side tip: You can add strftime style arguments to the upload_to argument,
storing the files in dated sub directory. e.g.

MEDIA_ROOT = ‘/home/myname/files/
upload_to=’/pictures/%Y/%b/%d’
file: abc.jpg
results in: /pictures/2008/May/09/abc.jpg

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Posterous
  • Tumblr
  • Twitter

Comments are closed.