Reputation: 136
django rest framework post request error Here is the image model
class Img(models.Model):
created_at=models.DateTimeField(auto_now_add=True)
author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="img")
picture=models.ImageField(upload_to='fake_picture',null=True,blank=True)
tags = TaggableManager(blank=True)
Here is the image serializer for model Img
class ImgSerializer(serializers.ModelSerializer):
tags = TagListSerializerField(required=False)
author = serializers.StringRelatedField(read_only=True)
# post = serializers.StringRelatedField(read_only=True)
class Meta:
model=Img
fields='__all__'
views.py
class ImgViewSet(viewsets.ModelViewSet):
parser_class = (FileUploadParser,)
permission_classes =[IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly]
authentication_classes =(TokenAuthentication,JSONWebTokenAuthentication)
queryset = Img.objects.all()
serializer_class=ImgSerializer
but when ever a post request to that particular api endpoint is triggered from the post man with key value pair as
picture:image.jpg
this is what the response is
IntegrityError at /api/img/
null value in column "author_id" violates not-null constraint
DETAIL: Failing row contains (4, fake_picture/2019-06-27_at_10-04-59.png, 2020-05-05 23:06:00.16071+00, null).
Request Method: POST
Request URL: http://localhost:8000/api/img/
Upvotes: 0
Views: 133
Reputation: 1921
Please try this
class ImgViewSet(viewsets.ModelViewSet):
..........
serializer_class=ImgSerializer
.......
def perform_create(self, serializer):
serializer.save(author=serializer.context['request'].user)
Upvotes: 1