在一个简单的博客应用程序中,当用户对帖子发表评论时,建议的方法是重定向到同一个变量路由或永久链接以显示新评论(在django中)?
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()
获取网址,但我认为不是剥离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 :(得分: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)