Answer the question
In order to leave comments, you need to log in
Error adding comment?
If you try to add a comment to a post through the form, it gives the following error.
IntegrityError at /post/7/comment/
NOT NULL constraint failed: blog_comment.post_id
But if you write a comment through the admin panel, then there are no errors and everything is ok. By the way, after I added a comment, then the link to the comment form disappears on the page. Why?
#models.py
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
pub_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.text
#views.py
def add_comment(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
add_comment_form = CommentForm(request.POST)
if add_comment_form.is_valid():
comment_form = add_comment_form.save(commit=False)
comment_form.author = request.user
comment_form.save()
return redirect('post_detail', pk=post.pk)
else:
add_comment_form = CommentForm()
return render(request, 'blog/add_comment.html', {'add_comment_form': add_comment_form})
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question