How to change django default files storage to cloudinary storage for media files?
I am working on django project. It is working fine with local storage and decided to use cloudinary for media storage then for some reason the file storage is not changing to cloudinary media storage.
Here's my settings.py file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"listings",
"rest_framework",
"rest_framework_simplejwt",
"corsheaders",
'django_filters',
'cloudinary_storage',
'cloudinary',
]
# Cloudinary config
CLOUDINARY_STORAGE = {
"CLOUD_NAME": config("CLOUDINARY_CLOUD_NAME"),
"API_KEY": config("CLOUDINARY_API_KEY"),
"API_SECRET": config("CLOUDINARY_API_SECRET"),
}
cloudinary.config(
cloud_name = config('CLOUDINARY_CLOUD_NAME'),
api_key = config('CLOUDINARY_API_KEY'),
api_secret = config('CLOUDINARY_API_SECRET')
)
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
model.py file:
class Amenity(models.Model):
name = models.CharField(max_length=100, unique=True)
icon = models.ImageField(upload_to='amenity_icons/', null=True)
I tried to upload with admin panel. It stores locally despite settings DEFAULT_FILE_STORAGE
to 'cloudinary_storage.storage.MediaCloudinaryStorage'
The environment configuration is loaded properly (I checked by printing). Here's debugging shell output:
>>> from django.conf import settings
>>> from django.core.files.storage import default_storage
>>> print(settings.DEFAULT_FILE_STORAGE)
cloudinary_storage.storage.MediaCloudinaryStorage
>>> print(default_storage.__class__)
<class 'django.core.files.storage.filesystem.FileSystemStorage'>
I will work if I manually specify storage in every image field in every model.
from cloudinary_storage.storage import MediaCloudinaryStorage
class Amenity(models.Model):
name = models.CharField(max_length=100, unique=True)
icon = models.ImageField(
upload_to='amenity_icons/',
null=True,
storage=MediaCloudinaryStorage
)
Your settings seems correct but you seem to be missing MEDIA_URL
. In your settings:
MEDIA_URL = '/media/' # or any prefix you choose
Also note that you don't need to set storage for user upload media files because it will use the default you already set in DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'