How can I upload images and videos and get the url as a response using django-rest-framework?

Kevin
Kevin Member Posts: 4

Hi, please help me out.

models.py

class Posts(models.Model):

    image = models.ImageField(null=False)

    video = models.FileField( null=False, validators=[FileExtensionValidator(allowed_extensions=['MOV','AVI','MP4','WebM'])])

    title = models.CharField(max_length=50)

    about = models.TextField()


serializers.py

class PostSerializers(serializers.ModelSerializer):

    class Meta:

        model = Posts

        fields = ['id', 'image', 'video', 'title', 'about']


views.py

@api_view(['GET', 'POST'])

def postList(request):

    if request.method == 'GET':

        posts = Posts.objects.all()

        serializer = PostSerializers(posts, many=True)

        return Response(serializer.data)

   

    elif request.method == 'POST':

        serializer = PostSerializers(data=request.data)

        if serializer.is_valid():

            post = serializer.save()

            image_url = cloudinary.CloudinaryImage(post.image.public_id).build_url()

            video_url = cloudinary.CloudinaryVideo(post.video.public_id).build_url()

            post.image = image_url

            post.video = video_url

            post.save()


            data = {

                "id": post.id,

                "image": image_url,

                "video": video_url,

                "title": post.title,

                "about": post.about

            }

            return Response(data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



When i tried testing the api using postman, i get this error, even if my image is the supported format and it isnt corrupted:

  raise Error(result["error"]["message"])

cloudinary.exceptions.Error: Invalid image file



Your response will be highly appreciated. Thank you.

Tagged:

Best Answer

  • Ranson
    Ranson Cloudinary Staff Posts: 25
    Answer ✓

    Hey Kevin,

    I looked over the error messages that are reaching our servers and the `cloudinary.exceptions.Error: Invalid image file` is because the asset that is being sent as an image is actually a video file, so it doesn't look like the logic to separate the requests and pass in the type parameter are functioning properly.

    The specific request that I looked into was passing this asset `file: samsung_Galaxy_future_tech_display_power_viral_video_shorts.mp4` as an image file during upload.


    You will need to specify the resource_type parameter when making upload requests


    For example, in a video upload

    cloudinary.uploader.upload("dog.mp4", 
      resource_type = "video",
      public_id = "myfolder/mysubfolder/dog_closeup"
    


Answers