1

I'm trying to setup a comment system for my posts in a project that I've been working on for the past couple of months, and I'm getting the following error when trying to use the post_id (the number or pk) to identify the post that the comment is being made on:

ValueError at /forum/post/15/comment/new/
Cannot assign "15": "Comment.post" must be a "Post" instance.

This is how I have setup the comments:

models.py:

class Post(models.Model):
    titulo  = models.CharField(max_length=150)
    contenido = MarkdownxField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    
    def formatted(self):
        return markdownify(self.contenido)

    def __str__(self):
        return self.titulo

    def get_absolute_url(self):
        return reverse("post-detail", kwargs={"pk": self.pk})
    
class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    name = models.ForeignKey(User, on_delete=models.CASCADE)
    body = MarkdownxField()
    date_added = models.DateTimeField(default=timezone.now)
    
    def __str__(self):
        return '%s - %s' % (self.post.titulo, self.name)

views.py:

class CommentCreateView(CreateView):
    model = Comment
    form_class = CommentForm
    #fields = ['body']
    template_name = "forum/comment_form.html"
    
    def get_post_id(request, post_id):
        post=Post.objects.get(id=post_id)

    class Meta:
        ordering=['-time']
    
    def form_valid(self, form):
        form.instance.post = self.kwargs['pk']
        return super().form_valid(form)
    
    def get_success_url(self):   
        return reverse_lazy('')

forms.py:

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['body']
        
        widgets = {
            'body': MarkdownxField()
        }

urls.py:

path('post/<int:pk>/comment/new/', CommentCreateView.as_view(), name='comment-create'),    
Selcuk
  • 57,004
  • 12
  • 102
  • 110
winston1420
  • 160
  • 9
  • hi, interesting, perhaps this might be of use https://stackoverflow.com/questions/37839867/django-error-cannot-assign-must-be-an-instance – jspcal Apr 05 '22 at 23:43

1 Answers1

1

You are trying to assign a string to form.instance.post, which is supposed to be a Post instance:

form.instance.post = self.kwargs['pk']

Try something like

form.instance.post = Post.objects.get(pk=int(self.kwargs['pk']))
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • That's a separate problem. I suggest you to accept this answer by clicking the check mark next to it if it fixed your original issue, then post your new code and your new error message as a new question to get better answers from the community. – Selcuk Apr 06 '22 at 00:45