I have created an API and am currently testing my post request with Postman. However, I keep getting this error.
views.py
def post(self, request, *args, **kwargs):
serializer = TagSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save(name=request.POST.get("name"),
language=request.POST.get("language"))
return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
else:
return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
serializers.py
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('id', 'name', 'language')
def create(self, validated_data):
return Tag.objects.create(**validated_data)
def to_representation(self, data):
data = super().to_representation(data)
return data
models.py
class Tag(models.Model):
name = models.CharField(max_length=256)
language = models.CharField(max_length=256)
objects = models.Manager()
def create(self, validated_data):
tag_data = validated_data.pop('tag')
Tag.objects.create(**tag_data)
return tag_data
def __str__(self):
return self.name or ''
CodePudding user response:
The name field in your tag model is not nullable. So it looks like you are trying to create a Tag model without a name value.
My guess is your request.POST is probably empty. Did you check it ? The recommanded way is to use request.data instead.
https://www.django-rest-framework.org/api-guide/requests/
By the way, if you want to use serializer, you can do all the process calling its functions.
So, you are supposed to check if the serializer is valid by calling
serializer.is_valid(raise_exception=True) and then create the object with save(). And if you want something more custom, you can override the .save() method of your serializer
def post(self, request, *args, **kwargs):
serializer = TagSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save() # the result contains the tag instance
It may be also more efficient if you use CreateAPIView directly instead
https://www.django-rest-framework.org/api-guide/generic-views/
ps: It can't see where you are going with serializer.save(tag_input).
