Saving file field uploads not in MEDIA_ROOT directory

Apr 29, 2015 · Updated: Jul 12, 2021 · by Tim Kamanin

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.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓