DEV Community

Cover image for Uploading images to Cloudinary Storage from a Django DRF Application.
success
success

Posted on

Uploading images to Cloudinary Storage from a Django DRF Application.

Sometimes while working on applications that require the use of images, a simple process like uploading images to a server can become difficult. If you deploy your application to a platform like Heroku, you can’t save images.

Alternatively, we could have our images stored in the database, but the database size will explode over time. Hence, a reason images should be stored in external services like Cloudinary, AWS S3, or Imgur.

The advantage Cloudinary has is that “configuration is quick and easy”. In this tutorial, we will learn about how to save images in Django using Cloudinary.

Cloudinary is an end-to-end image and video management solution for websites and mobile apps. It covers everything from image and video uploads, storage, manipulations, and optimizations to delivery.

Prerequisites

To follow along with this tutorial, you’ll need Python3 installed on your machine and virtualenv as well.

A basic understanding of Django would help the reader follow along better.

Setting up a new Django project

Let’s start by creating a new virtual environment.

A virtual environment allows you to create different spaces on your computer, with a different set of libraries and versions.

By creating a virtual environment, you’ll be able to separate the necessary library installation for a project, without having to install them globally.

Now, you create a virtual environment env in your preferred folder as shown below:

to install virtualenv on your machine run

$ pip3 install virtualenv

Now use your installed virtualenv to create a new virtual environment

$ virtualenv env

Here, we need to change directory to our specified project folder where our env is.

Now you can activate the virtual environment using the following command:

On Linux or Mac:

$ source env/bin/activate

On Windows:

$ .\env\Scripts\activate

After activation we can install the latest Django on our virtual environment using the following command:

$ pip3 install django

Now lets create our Imageapp project using the django admin command

$ django-admin startproject imageapp

Now lets create a django app to hold our models

$ django-admin startapp images

Let’s add our app to the list of installed apps. Navigate to our Imageapp directory and edit the settings.py file,
Your settings.py file should look like this



INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'images.apps.ImagesConfig',
    ]


Enter fullscreen mode Exit fullscreen mode

Setting up a Cloudinary Account

Now, let’s head over to the Cloudinary website to create a new account.
provide your details and we are good.

Installing Django cloudinary Stroage



pip3 install django-cloudinary-storage
pip3 install cloudinary
pip3 install pillow


Enter fullscreen mode Exit fullscreen mode

Next, we have to add Cloudinary to the list of installed apps, your settings.py something like this:



INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'images.apps.ImagesConfig',
    'cloudinary_storage',
    'cloudinary',
    ]


Enter fullscreen mode Exit fullscreen mode

Configuration

To use the Django Cloudinary library, we have to configure our cloud_name, api_key, and api_secret.

We can find our account-specific configuration credentials on the Dashboard page of the account console as shown below:

Image description

Dashboard page cloudinary

Now add the following config to the bottom of your settings.py file and fill in your credentials gotten from cloudinary in-between the quotes.



CLOUDINARY_STORAGE = {
    'CLOUD_NAME': 'your_cloud_name',
    'API_KEY': 'your_api_key',
    'API_SECRET': 'your_api_secret',
}


Enter fullscreen mode Exit fullscreen mode

Making Cloudinary our default file storage

Now need to add a default file storage above our CLOUDINARY_STORAGE config and set it to cloudinary as shown bellow:



MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'


Enter fullscreen mode Exit fullscreen mode

Creating a Django Model

Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.

In the photos directory, edit the models.py file and add the following lines of code to it:



from django.db import models

class Images(models.Model):
    title = models.CharField(max_length=255) # title of the image
    image = models.ImageField(upload_to='images') # image


Enter fullscreen mode Exit fullscreen mode

Now, let’s migrate our model to the database by running the commands below:



python3 manage.py makemigrations

python3 manage.py migrate


Enter fullscreen mode Exit fullscreen mode

A superuser has the permissions to create, edit, update, and delete data in Django admin. We create a superuser by running the command below:

python3 manage.py createsuperuser

Now let’s register the model of photos in the admin.py file, so we can modify it in the Django admin section.



from django.contrib import admin
from .models import Images

admin.site.register(Images)


Enter fullscreen mode Exit fullscreen mode

Now, we can log in to the admin page.

To login to the admin section, go to this link localhost:8000/admin and log in with our just created superuser details.

Now add photos as usual and you are good to go... your image will have a reference in your admin site which if u click it will open the image with the link showing cloudinary storage and in your cloudinary media library directory you will also find your uploaded image.

Conclusion

We have learned how Cloudinary provides a better way to handle media content for our webpage. We have also learned to upload images from a Django DRF apps.

Happy coding...

Top comments (6)

Collapse
 
debrabrown profile image
DebraBrown

I am a self-taught developer who loves to work on fronted as well as backed. I am currently working on Django and MongoDB. Spells to make someone go away

Collapse
 
successhycenth profile image
success

Sorry about that, please reach out if you have any questions or need assistance. successhycenth8@gmail.com

Collapse
 
keiru517 profile image
keiru517 • Edited

Thanks for this article.
How to get the uploaded file path?

Collapse
 
successhycenth profile image
success

Will be available in your Django admin or restframework endpoint if you’re building an api

Collapse
 
mallamsiddiq profile image
akinyemi sodiq

if its API, the field will automatically return the url and if you're working in django template.. the file field has the url attribute i.e assume the field is attachmet, call attachment.url

Collapse
 
swadexpress profile image
kawsar khan

Thanks :)