Home > other >  ValueError: Cannot assign "15": "Comment.post" must be a "Post" instan
ValueError: Cannot assign "15": "Comment.post" must be a "Post" instan

Time:04-06

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'),    

CodePudding user response:

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']))
  • Related