File uploads in Heroku deployment with Django

2019-08-23 14:28发布

问题:

So I was finally able to set up local + prod test project I'm working on.

# wsgi.py 
from dj_static import Cling, MediaCling

application = Cling(MediaCling(get_wsgi_application()))
application = DjangoWhiteNoise(application)

I set up static files using whitenoise (without any problems) and media (file uploads) using dj_static and Postgres for local + prod. Everything works fine at first... static files, file uploads.

But after the Heroku dynos restart I lose all the file uploads. My question is, --- Since I'm serving the media files from the Django app instead of something like S3, does the dyno restart wipe all that out too?

PS: I'm aware I can do this with AWS, etc, but I just want to know if thats the reason I'm losing all the uploads.

回答1:

Since I'm serving the media files from the Django app instead of something like S3, does the dyno restart wipe all that out too?

Yes!. That's right. According to the Heroku docs:

Each dyno gets its own ephemeral filesystem, with a fresh copy of the most recently deployed code.

See, also this answer and this answer.

Conclusion: For media files (the uploaded ones), you must use some external service (like S3 or something). whitenoise is just for static files. See here why whitenoise is not suitable for serving user-uploaded (media) files.