2017-02-28 105 views
0

在一个简单的博客应用程序中,当用户对帖子发表评论时,推荐重定向到同一变量路由或固定链接以显示新评论(在django中)的方式是什么?重定向到表单POST后重新加载当前页面视图

urlpatterns = [ 
    ... 
    url(r'^comments/(?P<post_id>[0-9]+)$', views.comments, name="thread"), 
    url(r'^post/comment/$', views.post_comment, name="post_comment"), 
] 

在视图中,我可以request.get_full_path()获得url,但我相信,而不是剥离post_id有一个更好的方式将它传递给重定向。例如视图(但不是右):

def post_comment(request): 

    author = User.objects.get(user=request.user) 
    new_comment = request.POST.get('commentContent', None) 
    parent_object = None 
    comment = Comment.create(author=author, 
          new_comment=new_comment, 
          parent=parent_object) 

    comment.save() 
    return redirect('/comments/{}'.format(comment.post.id)) 

提交评论表单将记录:

[28/Feb/2017 05:21:33] "POST /post/comment/ HTTP/1.1" 302 0 
[28/Feb/2017 05:21:33] "GET /comments/{{post_id}} HTTP/1.1" 200 44831 

和形式的职位,但系统页面不会重新加载/重定向

感谢

回答

0

您可以使用反向重定向:

from django.core.urlresolvers import reverse 

# at the end of your view 
redirect_to = reverse('blog:thread', kwargs={'post_id': post.id}) 
return redirect(redirect_to) 
相关问题