How to upload images and videos from the same field to Cloudinary on Django Framework

Hey guys, welcome to the Devmaesters website. In this article, I will explain how you can create a field in Django model that accepts both image and video files and stores them on the Cloudinary hosting platform.

To follow along with this tutorial, you need to have already set up Cloudinary hosting in your Django project. If you haven't done so, I recommend checking out the following articles on our website: How to Host Media Files on Cloudinary for Django Projects.

Once Cloudinary hosting has been set up in your project, you can proceed with the following steps:

Step 1: Import the required modules

Import FileSystemStorage, VideoMediaCloudinaryStorage, MediaCloudinaryStorage, as shown below

from cloudinary_storage.storage import VideoMediaCloudinaryStorage, MediaCloudinaryStorage
from django.core.files.storage import FileSystemStorage

Step 2: Create a custom storage class and override the get_valid_name method

class CustomStorage(FileSystemStorage):
    def get_valid_name(self, name):
        if name:
            if name.endswith(('.jpg', '.jpeg', '.png', '.gif')):
                # Images will be stored in Cloudinary using the MediaCloudinaryStorage
                return 'images/' + name
            elif name.endswith(('.mp4', '.mov', '.avi')):
                # Videos will be stored in Cloudinary using the VideoMediaCloudinaryStorage
                return 'videos/' + name
        # If the file extension is unknown or the instance/filename is not available,
        # use the default location and apply the default valid name logic
        return super().get_valid_name(name)

Step 3: Define your model with the custom storage class and override the save method

class TestUpload(models.Model):
    name = models.CharField(max_length=50)
    test_upload = models.FileField(upload_to = 'files/', storage=CustomStorage())

    def save(self, *args, **kwargs):
        if self.test_upload:
            if self.test_upload.name.endswith(('.jpg', '.jpeg', '.png', '.gif')):
                # Use MediaCloudinaryStorage for images
                self.test_upload.storage = MediaCloudinaryStorage()
            elif self.test_upload.name.endswith(('.mp4', '.mov', '.avi')):
                # Use VideoMediaCloudinaryStorage for videos
                self.test_upload.storage = VideoMediaCloudinaryStorage()

        super().save(*args, **kwargs)

Step 4: Finally your code should look like the on shown below;

class CustomStorage(FileSystemStorage):
    def get_valid_name(self, name):
        if name:
            if name.endswith(('.jpg', '.jpeg', '.png', '.gif')):
                # Images will be stored in Cloudinary using the MediaCloudinaryStorage
                return 'images/' + name
            elif name.endswith(('.mp4', '.mov', '.avi')):
                # Videos will be stored in Cloudinary using the VideoMediaCloudinaryStorage
                return 'videos/' + name
        # If the file extension is unknown or the instance/filename is not available,
        # use the default location and apply the default valid name logic
        return super().get_valid_name(name)

class TestUpload(models.Model):
    name = models.CharField(max_length=50)
    test_upload = models.FileField(upload_to = 'files/', storage=CustomStorage())

    def save(self, *args, **kwargs):
        if self.test_upload:
            if self.test_upload.name.endswith(('.jpg', '.jpeg', '.png', '.gif')):
                # Use MediaCloudinaryStorage for images
                self.test_upload.storage = MediaCloudinaryStorage()
            elif self.test_upload.name.endswith(('.mp4', '.mov', '.avi')):
                # Use VideoMediaCloudinaryStorage for videos
                self.test_upload.storage = VideoMediaCloudinaryStorage()

        super().save(*args, **kwargs)

In the code above, whenever a user uploads a file, it checks whether it's an image or a video and assigns the appropriate media storage for saving the file (i.e., VideoMediaCloudinaryStorage for videos and MediaCloudinaryStorage for images).

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
No comment yet

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.