[Django]-How to deploy media files in django-heroku?

2👍

Follow these steps:

  1. Add Cloudinary Addon to your Heroku app.

  2. Click on cloudinary and install it.

  3. Then click on Cloudinary addon.

  4. From this dashboard you will be able to see your credentials to connect with.

Then go to your project:

  1. IN your terminal type these commands:
pip install django-cloudinary-storage
    
pip install cloudinary
    
pip install Pillow
  1. In your settings.py, add
INSTALLED_APPS = [
       'django.contrib.staticfiles',   
       'cloudinary_storage',
       'cloudinary',
        ]
    
CLOUDINARY_STORAGE = {
             'CLOUD_NAME': 'your_cloud_name',
             'API_KEY': 'your_api_key',
             'API_SECRET': 'your_api_secret'
            }
    
MEDIA_URL = '/media/'  # or any prefix you choose
     
DEFAULT_FILE_STORAGE='cloudinary_storage.storage.MediaCloudinaryStorage'

In models.py:

10.

class TestModel(models.Model):
             name = models.CharField(max_length=100)
             image = models.ImageField(upload_to='images/', 
             blank=True)
  1. Now, in order to put this image into your template, you can
    just type:
        <img src="{{ test_model_instance.image.url }}" alt="{{ 
        test_model_instance.image.name }}">
  1. requirements.txt:
...
cloudinary==1.17.0
django-cloudinary-storage==0.2.3

3👍

The package django-heroku would not provide this functionality out-of-the-box (due to restrictions on heroku side it is impossible to achieve seamless deployment and development of media files). In development one must load the media files through:

urlpatterns = [
    ....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In production the static files, as some users referred above must be served from an external source. Here are the tips I’m currently following: https://web.archive.org/web/20170607080235/http://djangobook.com/serving-files-production/

1👍

I just want to explain further what others have been saying that Andre failed to understand. When you deploy your project, those media files are not there – they are added when using the application and are available for that period ONLY. When the dyno goes to sleep your application is more or less redeployed (everything is installed again for use) and is exactly the same way you first deployed it – without the media files.

👤E. A.

Leave a comment