I'm building an API with the Django Rest Framework for a site that allows users to create posts, and comment on those posts. I'm able to create posts from the API fine, but when I try to create a comment I get the following error:
NOT NULL constraint failed: app_comment.post_id
my models:
class Post(models.Model):
owner = models.ForeignKey('auth.User', related_name = 'posts')
post_title = models.CharField(max_length=200)
post_description = models.CharField(max_length=1000)
class Comment(models.Model):
user = models.ForeignKey(User, related_name = 'comments')
post = models.ForeignKey(Post, related_name = 'comments')
text = models.CharField(max_length=1000)
and my comment serializer:
class CommentSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
post = serializers.ReadOnlyField(source='post.id')
class Meta:
model = Comment
fields = ('id', 'text', 'user', 'post')
and my comment view:
class PostCommentList(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticated,
IsOwnerOrReadOnly,)
serializer_class = CommentSerializer
def get_queryset(self):
post = self.kwargs['post_pk']
post = Post.objects.get(pk = post)
return post.comments.all()
def perform_create(self, serializer):
post = self.kwargs['post_pk']
print("creating a comment from " + str(self.request.user) + " on post " + str(post) +" : "+ str(Post.objects.get(pk = post)))
serializer.save(user = self.request.user)
serializer.save(post = self.kwargs['post_pk'])
When attempting to create a comment on a post, I see the correct information being printed out (i.e. 'creating a comment from user on post 6 : Post object').
Why are my comments not being created with the correct post_id?
get_querysetandperform_create? I guess it should work normally if you don't do it. Could you check it, please?