Python Django-按comment delete后重定向
我有一个从帖子中删除评论的代码Python Django-按comment delete后重定向,python,django,Python,Django,我有一个从帖子中删除评论的代码 def comment_remove(请求,主键): comment=获取对象或404(comment,pk=pk) comment.delete() 返回重定向('Post-detail',pk=Post.pk) 它删除注释,但抛出一个错误,即未定义名称“post” 我在我的views.py中有一个与上面相同的函数,它具有相同的post.pk,可以很好地工作 @需要登录\u def在帖子中添加评论(请求、主键): post=获取对象或404(post,pk=p
def comment_remove(请求,主键):
comment=获取对象或404(comment,pk=pk)
comment.delete()
返回重定向('Post-detail',pk=Post.pk)
它删除注释,但抛出一个错误,即未定义名称“post”
我在我的views.py
中有一个与上面相同的函数,它具有相同的post.pk
,可以很好地工作
@需要登录\u
def在帖子中添加评论(请求、主键):
post=获取对象或404(post,pk=pk)
如果request.method==“POST”:
表单=评论表单(request.POST)
如果form.is_有效():
comment=form.save(commit=False)
comment.post=post
comment.author=request.user
#comment.author.photo=object.author.profile.image.url
comment.save()
返回重定向('Post-detail',pk=Post.pk)
其他:
form=CommentForm()
返回呈现(请求'blog/add_comment_to_post.html',{'form':form})
评论模式
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=20)
text = models.TextField(max_length=200)
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
谁能给我解释一下,问题出在哪里?
它不接受post.pk而接受comment.pk吗?你可以像这样从comment对象中选择
pk
comment = get_object_or_404(Comment, pk=pk)
....
return redirect('Post-detail', pk=comment.post_id)
你在
Comment
model中有帖子参考吗?#shafik我在下面的答案中添加了我的models.py