If you have a question that "How to keep your uploaded media files saved on Heroku for a Django application?" for free and that too without S3 you are at right place... 😀
Heroku is a great hosting provider especially for Django based projects I really like it. But the issue we face is that we choose maybe free dyno or use Hobby most of the time for smaller projects now coming to issue which is that whenever we store/upload an image and as soon as the server restarts the uploaded media files are gone which can cause alot of confusion how that happened and where are these files gone.
Heroku explains in its documentation here why it happens in a very complicated language but in short you cannot store your media or dynamic stuff which if uploaded after the deployment. On every refresh heroku delete uploaded media files and place the fresh deployed copy of code.
Couple of solutions they propose:
In this blog I will be showing you guys how to connect Cloudinary with your Django app to store your Media files. We are doing this because we are not able to store our images Media on our heroku server specifically.
Add Cloudinary Addon to your Heroku app
click on cloudinary and install it
and connect it to your heroku app like I did here with "computervisiontools" a Django app in my heroku dashboard Also choose a plan to connect with I am choosing Free version here.
then click on just added addon Cloudinary to move to its dashboard.
From this dashboard you will be able to see your credentials to connect with
Use your CLOUD_NAME, API_KEY and API_SECRET to connect cloudinary to your django project
in your requirements.txt file add
...
cloudinary==1.17.0
django-cloudinary-storage==0.2.3
Install these dependencies
in settings.py file
add following to your settings file
INSTALLED_APPS = [
....
'cloudinary_storage',
'django.contrib.staticfiles',
....
'cloudinary',
]
and towards the end of file add
CLOUDINARY_STORAGE = {
'CLOUD_NAME': 'YOUR_CLOUD_NAME',
'API_KEY': 'YOUR_API_KEY',
'API_SECRET': 'YOUR_API_SECRET',
}
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
now whenever an image is uploaded its directly uploaded to cloudinary you can use all of the cloudinary features as well for manipulating images but if you don't still you have been able to store your media upto 10GB for free and on a very fast service it will cache and speed up your load times of images. I hight recommend it for SEO as well.