0

I want to pass a 'success' message to the post, after a new comment is added. Here are the views:

@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)

and

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)

The problem is that, messages are not displayed immediately after redirecting to post with new comment. They are displayed however, when I navigate to other pages.

I guess this is because the context_instance = RequestContext(request) is not properly conveyed from comment to post views. So I tried other redirect methods like render_to_respons and redner(reverse( , but could not manage to solve the issue. So appreciate your hints.

4

1 回答 1

1

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

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

return render(request, "article/post.html", d)
于 2015-10-03T10:41:19.357 回答