【问题标题】:Django how to pass message in return redirect?Django如何在返回重定向中传递消息?
【发布时间】:2015-10-03 10:27:43
【问题描述】:

我想在添加新评论后向帖子传递“成功”消息。以下是观点:

@login_required
def add_comment(request, post_slug):  

    p= Article.objects.get(slug=post_slug)
    cform = CommentForm(request.POST)
    if cform.is_valid():
        c = cform.save(commit = False)
        c.post = p
        c.body = cform.cleaned_data['body']
        c.author = request.user
        c.save()
            messages.success(request, "Comment was added") 
     else:
            messages.error(request, "Comment Invalid!") 

    return redirect('article.views.post_withslug', post_slug=post_slug)

def post_withslug(request, post_slug):
    post = Article.objects.get(slug = post_slug)
    comments = Comment.objects.filter(post=post)
    d = dict(post=post, comments=comments, form=CommentForm(), 
             user=request.user)
    d.update(csrf(request))
    return render_to_response("article/post.html", d)

问题是,在重定向到带有新评论的帖子后,消息不会立即显示。但是,当我导航到其他页面时,它们会显示出来。

我猜这是因为 context_instance = RequestContext(request) 没有正确地从评论传递到帖子视图。所以我尝试了其他重定向方法,如 render_to_responsredner(reverse( ,但可以 无法解决问题。非常感谢您的提示。

【问题讨论】:

    标签: django django-views django-messages


    【解决方案1】:

    问题出在post_withslug 视图中。您实际上并没有在该视图中使用 RequestContext 。 d 是标准字典。因此,上下文处理器不会运行,消息也不会出现。

    您应该使用render 快捷方式而不是render_to_response

    return render(request, "article/post.html", d)
    

    【讨论】:

    • 非常感谢丹尼尔!更改为render 解决了这个问题。不知道我没注意到什么。
    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 2010-10-10
    • 2013-11-19
    • 2023-03-03
    • 1970-01-01
    • 2012-06-06
    • 2020-06-04
    • 1970-01-01
    相关资源
    最近更新 更多