In this tutorial, we will learn how to upload images to Cloudinary from a Django application.
Sample Project
$ mkdir upload-to-cloudinary && cd upload-to-cloudinary
$ pipenv install django
$ pipenv shell
$ django-admin startproject config .
$ python manage.py startapp uploads
Open the models.py in uploads applications and make it look like the following:
from django.db import models
class Upload(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images/')
def __str__(self):
return self.title
Open the settings.py and install our new application.
INSTALLED_APPS = [
...
'uploads.apps.UploadsConfig',
]
To be able to use ImageField, we have to install Pillow.
$ pipenv install Pillow
Now we have to make a migration, type the following command in the terminal:
$ python manage.py makemigrations
If you get the following error:
TypeError: argument of type 'PosixPath' is not iterable
Then you have to convert the path to be a string:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': str(BASE_DIR / 'db.sqlite3'),
}
}
Now run the migrate command:
$ python manage.py migrate
We have to create a superuser to be able to use the admin.
$ python manage.py createsuperuser
Now we have a superuser and will be able to log into the admin.
$ python manage.py runserver
Open the browser and go to http://localhost:8000/admin
from django.contrib import admin
from .models import Upload
admin.site.register(Upload)
$ pipenv install cloudinary dj3-cloudinary-storage
Open settings.py and make the following changes:
INSTALLED_APPS = [
...
'cloudinary',
]
CLOUDINARY_STORAGE = {
'CLOUD_NAME': 'YOUR CLOUDINARY CLOUD NAME',
'API_KEY': 'YUOR CLOUDINARY API KEY',
'API_SECRET': 'YOUR CLOUDINARY API SECRET KEY',
}
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
Now run python manage.py migrate to install cloudinary app.Share this: