djangodjango-class-based-viewscreate-view

How do I link a comment to a post using a class based view


Using django version 2.2 I have created a blog app. I am trying to connect a comment to a post using a class based view (CreateView). However when i test the application I am getting an error which says:

IntegrityError at /post/7/comment/ NOT NULL constraint failed: blog_comment.post_id

I tried to reuse the CreatePostView but i am unse how in the view.py to link the comment to the post.

My view is as follows:

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = ['text',]

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

My model is as follows:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

class Comment(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
    author = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

    def approve(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text

In my url I have:

path('post/<int:pk>/comment/', CommentCreateView.as_view(), name='comment-create'),

So what I am expecting is to some how resolve this error and have it being able to add a comment to post via the front end. I can add a comment to a post via the admin site seemingly with now issue so the problem must lie with the view?


Solution

  • You can add it in the view like below

    class CommentCreateView(LoginRequiredMixin, CreateView):
        model = Comment
        fields = ['text',]
    
        def form_valid(self, form):
            form.instance.author = self.request.user
            form.instance.post_id = self.kwargs['pk']
            return super().form_valid(form)