0

I'm trying to save some data like Image and it's info with POST method from Postman. But I got an error: init() got an unexpected keyword argument 'title'. Here is my code:

1.models.py

from django.db import models
class Images(models.Model):
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    image = models.ImageField()
  1. serializers.py
from rest_framework import serializers
from .models import Images

class ImgSerializer(serializers.ModelSerializer):
    class Meta:
        model = Images
        fields = ["title", "description", "image"]

    def create(self, validated_data):
        return ImgSerializer(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.description = validated_data.get('description', instance.description)
        instance.save()
        return instance
  1. views.py
class ImgApi(APIView):
    parser_classes = (MultiPartParser, FormParser)
    def post(self, request):
        serializer = ImgSerializer(data=request.data)
        if serializer.is_valid():
            try:
                serializer.save()
            except Exception as e:
                logger.error(e)
                return Response(data={'msg':f'{e}'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            return Response(data=json_data,
                            status=status.HTTP_201_CREATED)

And things in Postman: Things in Postman

How should I fix this problem?

1 Answer 1

1

Your problem is from ImgSerializer.create() method:

  • serializer.save() will call ImgSerializer.create() because the serializer is not initialized with instance keyword.
  • In serializer create method, ImgSerializer(**validated_data) construct new serializer instance, which will call ModelSerializer.__init__ method. But since you use unpack operator (**validated_data), you actually pass title, description and image keyword args to __init__ method, which are not recognized by the method.

So instead of ImgSerializer(**validated_data), you should use ImgSerializer(data=validated_data).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.