7
When studying Django, the typical way to handle uploading files was to create a folder media
on the server - establishing a MEDIA_ROOT
and a MEDIA_URL
in the settings.py
- where any uploaded file would go. In the templates, a FileField
or ImageField
is created, whose upload_to
is related to MEDIA_ROOT
. In production, the webserver itself (e.g., Apache) is expected to serve the content of the URL /media
, leaving only dynamic content to Django.
So far so good, the problem is that I would like to restrict the access of files "uploaded" to logged in users, according to some access control criteria. What is the right way to do this? Is it Django’s or Apache’s responsibility to do this access control? (and if it’s Apache, how to make it use Django’s permissions system?)
For reference, here’s how my virtual host (usage Django 1.4.14):
Alias /media/ /var/www/vhosts/example.com/httpdocs/media/
Alias /static/ /var/www/vhosts/example.com/httpdocs/static/
WSGIDaemonProcess exemplo threads=15 processes=5
WSGIProcessGroup exemplo
WSGIScriptAlias / /var/www/vhosts/example.com/exemplo.wsgi
P.S. For performance reasons, I would prefer that not all the /media
had access control - the case of files uploaded by the user that are universally accessible is more frequent than the case where the file is restricted. I could assign a subfolder to them (ex.: /media/restrito
) and let Django take care of that folder, but I don’t know how to do it with just the Alias
and WSGIScriptAlias
. Maybe I need the mod_rewrite
also, I do not know... Anyway, I am quite lost, any reference on the subject would be very welcome.
We did this here at the company, I hope it helps. http://blog.wearefarm.com/2015/02/09/contact-form-uploads/
– Vanderson Ramos
@Vanderson seems like a pretty smart solution! Too bad I’m using Apache, not Nginx... :( With a little luck, maybe Apache has some functionality equivalent to
X-Accel-Redirect
. Does anyone know any?– mgibsonbr
I found this link. http://francoisgaudin.com/2011/03/13/serving-static-files-with-apache-while-controlling-access-with-django/
– Vanderson Ramos
@Vanderson Yes, it seems to me to be exactly the same functionality. Thanks! I would still have to solve the other half of the problem (make the template store the uploaded files in an unreachable folder) but already helped a lot.
– mgibsonbr