I have the following model field in a django project:
headshot = models.ImageField(upload_to='/tmp', blank=True, null=True)
settings.py
# format <project>/<app>
MEDIA_ROOT = '/home/username/webapps/django/myproject/books/media/'
I have created a directory: /home/username/webapps/django/myproject/books/media/tmp
and gave it chmod 777
permissions.
I get the following error when I try to add a new image:
SuspiciousOperation at /admin/books/author/add/
Attempted access to '/tmp/Comment.png' denied.
Request Method: POST
Request URL: http://username.webfactional.com/app/admin/books/author/add/
Django Version: 1.3.1
Exception Type: SuspiciousOperation
Exception Value:
Attempted access to '/tmp/Comment.png' denied.
Exception Location: /home/username/webapps/django/lib/python2.7/django/core/files/storage.py in path, line 234
Python Executable: /usr/local/bin/python
Python Version: 2.7.1
Does anyone know what I'm doing wrong? Do I need .htaccess
or some other settings to be able to write to this directory or is there something wrong with my Django config?
I would still like to know what chmod
values to use and how to set MEDIA_URL
. I'm thinking I might need to do something in urls.py
for MEDIA_URL
.
My project is set up on the webhost Webfaction if that makes a difference.
I see you've marked this as answered, but still have some questions in your answer. Here is how I have this set up, in case you are still working on it.
Set up a new app for media (via the webfaction control panel). I used the "static_only" application because it should prevent users from uploading scripts and running them. You could also use one of the "static/cgi/php". Creating a new app for this (instead of using Django and making a new view) is good practice because it will have a lower resource overheard. Django is overkill for serving static files (images, css files, javascript files, etc.).
Bind your new media (static_only, or whatever you used) app to some URL, again using the webfaction control panel. I bound mine to media..com.
MEDIA_URL
should be set to the URL you can access your media through, andMEDIA_ROOT
should be the root directory for the media app. Thus, in my settings.py file I have:It's best to do the same thing for
STATIC_ROOT
andSTATIC_URL
.As far as permissions go, the defaults should be OK - if you have troubles with that just ask.
Fixed it. Seems like the answer was to use upload_to='tmp' instead of upload_to='/tmp'.