Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save FileField file uploads someplace other than MEDIA_ROOT?

Tags:

django

Can I use FileField to handle a file, but store it someplace not under MEDIA_ROOT/MEDIA_URL but somewhere else entirely.

Seeking is to ensure it is not downloadable; although denying read permissions would do the trick here's hoping for something better... like a different directory altogether.

like image 231
John Mee Avatar asked Nov 15 '09 01:11

John Mee


2 Answers

There are a few ways to do this.

First, you can take a look at handling uploaded files from the Django docs. If you read it over, basically you can handle the upload of the file within your view in the same part where you are processing your form.

Another option, and one which I think would be better is to use a custom file storage system. You could do this very simply using the existing one as a base but simply change the location, then use it as an argument in your FileField. For example:

from django.core.files.storage import FileSystemStorage

my_store = FileSystemStorage(location='/some/other/dir')

class SomeModel(models.Model):
      file = models.FileField(storage=my_store)

Hope that helps!

like image 72
Bartek Avatar answered Sep 30 '22 20:09

Bartek


Considering that the only actual use of MEDIA_ROOT in all of Django is to determine where uploaded files are stored, seems like it would make more sense to just point MEDIA_ROOT where you want your uploaded files, and then use a different setting for the path to your static assets. This is the approach taken by Pinax and django-staticfiles, which use STATIC_URL and STATIC_ROOT settings.

Note that even the documentation page on serving static assets in development no longer recommends using MEDIA_ROOT for that purpose, it demonstrates using your own STATIC_DOC_ROOT setting.

like image 26
Carl Meyer Avatar answered Sep 30 '22 21:09

Carl Meyer