Saving file field uploads not in MEDIA_ROOT directory

29 Apr · by Tim Kamanin · 1 min read

I had a requirement recently to upload files to some kind of a private directory, not accessible via www. Of course, I used Django model's FileField to solve the task, but the problem was in a fact that by default, FileField saves uploads under MEDIA_ROOT which is not what I wanted.

Luckily, Django has a pretty simple solution to the problem, all you need is to extend default file storage a little bit and pass it to our file field, like that:

1) At first lets define our private storage path, it's better to put it into your app configuration, like this:


2) Now update your model:

from django.conf import settings
from import FileSystemStorage
from django.db import models

private_storage = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT)

class MyModel(models.Model):
  upload = models.FileField(storage=private_storage)

That's all. Make sure your 'private' directory exists and that should be it.

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials