我无法在帖子的现有评论列表中添加新评论。这是一个模型:
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
body = models.TextField()
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
commented_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'Commented by {self.commented_by} on {self.post}.'以下是视图:
def post_detail(request, id):
post = Post.objects.get(id=id)
comments = post.comments.all().order_by('-commented_on')
total_comments = post.comments.all().count()
form = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST, instance=post)
if form.is_valid():
instance = form.save(commit=False)
instance.post = post
instance.save()
context = {
'post' : post,
'comments' : comments,
'form' : form,
'total_comments' : total_comments,
}
return render(request, 'blog/detail.html', context)发布于 2021-01-11 12:54:50
基本上,当您尝试保存新注释时,您正在将错误的模型实例传递给表单:
form = CommentForm(request.POST, instance=post)
^^^^^^^^^^^^^实际上并不需要这样做,您可以通过以下方式简单地声明表单实例:
form = CommentForm(request.POST)下面是一个很小的重构代码:
def post_detail(request, id):
post = Post.objects.get(id=id)
form = CommentForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
instance = form.save(commit=False)
instance.post = post
# instance.comment_by = request.user
instance.save()
comments = post.comments.all().order_by('-commented_on')
total_comments = comments.count()
context = {
'post' : post,
'comments' : comments,
'form' : form,
'total_comments' : total_comments,
}
return render(request, 'blog/detail.html', context)https://stackoverflow.com/questions/65661456
复制相似问题