Home > Software design >  Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Pro
Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Pro

Time:11-03

models.py


  from django.contrib.auth.models import User
 
     class Profile(models.Model):
         name = models.OneToOneField(User,on_delete=models.CASCADE,related_name='user')
         bio = models.CharField(max_length=300)
         photo = models.ImageField(upload_to='images/profile_photos/')
     
         def __str__(self):
             return self.name.username
     class Comment(models.Model):
         comment_user = models.ForeignKey(Profile, on_delete=models.CASCADE)
         comment_text = models.TextField(blank=True)
         todo = models.ForeignKey(Todo, on_delete=models.CASCADE,related_name='comment')
         created = models.DateTimeField(auto_now_add=True)
         updated = models.DateTimeField(auto_now=True)
         active = models.BooleanField(default=False)
 
         def __str__(self):
             return self.comment_text  " "  self.comment_user.name.username

serializers.py

class CommentSerializer(ModelSerializer):
    comment_user = serializers.StringRelatedField(read_only=True)
    class Meta:
        model = Comment
        exclude = ('todo',)
        #fields = "__all__"

views.py

class CommentCreateApiView(generics.CreateAPIView):
    serializer_class = CommentSerializer
    #permission_classes = [TodoCreatorOrReadOnly]
    # def get_queryset(self):
    #     return Comment.objects.all()
    def perform_create(self, serializer):
        id = self.kwargs['todo_id']
        todo_item = Todo.objects.get(pk=id)
        user_comment = self.request.user
        print(user_comment)
        comment_query = Comment.objects.filter(todo=todo_item,comment_user__name__username=user_comment).exists()
        if comment_query:
            raise ValidationError('User Comment is already exist..!')
        else:
           serializer.save(todo=todo_item,comment_user=user_comment)


errors

 File "D:\python_projects\todo_project\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__
    raise ValueError(
ValueError: Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Profile" instance.

I have tried several times to comment on a specific todo item. A single authenticated user can write one comment on a single todo item. When I have been sending a post request the response shows Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Profile" instance. I guess the problem occurs inside below the line: serializer.save(todo=todo_item,comment_user=user_comment)

CodePudding user response:

It is indeed because of this line:

serializer.save(todo=todo_item,comment_user=user_comment)

user_comment is a User instance, but comment_user expects a Profile instance as the error suggests.

So if you did intend to use the profile of the curent user you can do:

serializer.save(todo=todo_item, comment_user=user_comment.user)

Where .user is the related name to access Profile from User. (You might want to change the related name to something better, like profile)

CodePudding user response:

view.py

class CommentCreateApiView(generics.CreateAPIView):
    serializer_class = CommentSerializer
    #permission_classes = [TodoCreatorOrReadOnly]
    # def get_queryset(self):
    #     return Comment.objects.all()
    def perform_create(self, serializer):
        id = self.kwargs['todo_id']
        todo_item = Todo.objects.get(pk=id)
        user_comment = self.request.user
        print(user_comment)
        comment_query = Comment.objects.filter(todo=todo_item,comment_user__name__username=user_comment).exists()
        if comment_query:
            raise ValidationError('User Comment is already exist..!')
        else:
           serializer.save(todo=todo_item, comment_user=user_comment.user)
  • Related