我有一个方法可以在基础中插入一个新的Comment
,然后重新定向回上一个帖子,可以是任意一个。所以,为此,我制定了以下规则:
return redirect(reverse('blog:post', args = (post_id,)))
有了它,页面将被重定向回到之前正在阅读的Post
,方法是将id
传递给网址。
现在问题是表格无效。我想显示错误消息,但我认为它现在的方式,正在重新创建表单,删除任何消息。因此,在else
条件下,我想要,而不是重定向,再次呈现它并显示消息。我这样做了:
return render(request, 'blog/post.html', post_id = post_id)
但是,无论参数中的id
如何,我都需要回到相同的页面。我需要像post_id
函数那样传递redirect
,但我找不到办法。
这是整个方法:
def write_comment(request, post_id):
"""
Write a new comment to a post
"""
form = CommentForm(request.POST or None)
if form.is_valid():
post = Post.objects.get(pk = post_id)
post.n_comments += 1
post.save()
comment = Comment()
comment.comment = request.POST['comment']
comment.created_at = timezone.now()
comment.modified_at = timezone.now()
comment.post_id = post_id
comment.user_id = 2
comment.save()
return redirect(reverse('blog:post', args = (post_id,)))
else:
# Need to pass the parameter here, in order to not recreate the form
return render(request, 'blog/post.html')
我的班级视图用于通过网址显示Post
,具体取决于id
:
url(r'^post/(?P<id>[0-9]+)/$', views.GetPostView.as_view(), name = 'post'),
GetPostView
:
class GetPostView(TemplateView):
"""
Render the view for a specific post and lists its comments
"""
template_name = 'blog/post.html'
def get(self, request, id):
return render(request, self.template_name, {
'post': Post.objects.get(pk = id),
'comments': Comment.objects.filter(post = id).order_by('-created_at'),
'form': CommentForm()
})
答案 0 :(得分:1)
您应该将表单作为上下文变量(上下文参数)传递。
render(request, 'blog/post.html', context={"form": form})
您可能还想重新组织一些事情。我会将评论处理逻辑与GetPostView
结合起来。我会尝试将get
中的逻辑移到get_context_data
,这将在渲染get / post时使用。然后添加post
方法(而不是write_comment
,尽管您当然可以从post
调用该方法。在那里,如果您需要按原样呈现页面,只需尝试调用super
方法的post
版本。
class GetPostView(TemplateView):
"""
Render the view for a specific post and lists its comments
"""
template_name = 'blog/post.html'
def get(self, request, id):
self.request = request
self.id = id
return super(GetPostView, self).get(request, self.id)
def post(self, request, id):
"""
Process comment
"""
self.form = CommentForm(request.POST or None)
if self.form.is_valid():
post = Post.objects.get(pk = id)
post.n_comments += 1
post.save()
comment = Comment()
comment.comment = request.POST['comment']
comment.created_at = timezone.now()
comment.modified_at = timezone.now()
comment.post_id = id
comment.user_id = 2
comment.save()
return redirect(reverse('blog:post', args = (id,)))
else:
return self.get(request, id)
def get_context_data(self, **kwargs):
form = self.form if hasattr(self, 'form') else CommentForm()
return {
'post': Post.objects.get(pk = self.id),
'comments': Comment.objects.filter(post = self.id).order_by('-created_at'),
'form': form
}
免责声明:我没有运行此代码,因此可能会犯一个愚蠢的错误。如果你指出它们,我会尝试清理它。