示例#1
0
def blog_post_detail(request, slug, template="blog/blog_post_detail.html"):
    """
    Display a blog post.
    """
    # Create two comment forms - one with posted data and errors that will be
    # matched to the form submitted via comment_id, and an empty one for all
    # other instances.
    commenter_cookie_prefix = "mezzanine-blog-"
    commenter_cookie_fields = ("name", "email", "website")
    comment_data = {}
    for f in commenter_cookie_fields:
        comment_data[f] = request.COOKIES.get(commenter_cookie_prefix + f, "")
    blog_posts = BlogPost.objects.published(for_user=request.user)
    blog_post = get_object_or_404(blog_posts, slug=slug)
    posted_comment_form = CommentForm(request.POST or None, 
                                      initial=comment_data)
    unposted_comment_form = CommentForm(initial=comment_data)
    if request.method == "POST" and posted_comment_form.is_valid():
        comment = posted_comment_form.save(commit=False)
        comment.blog_post = blog_post
        comment.by_author = (request.user == blog_post.user and
                             request.user.is_authenticated)
        comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR",
                                              request.META["REMOTE_ADDR"])
        comment.replied_to_id = request.POST.get("replied_to")
        comment.save()
        response = HttpResponseRedirect(comment.get_absolute_url())
        # Store commenter's details in a cookie for 90 days.
        cookie_expires = 60 * 60 * 24 * 90
        for f in commenter_cookie_fields:
            cookie_name = commenter_cookie_prefix + f
            cookie_value = request.POST.get(f, "")
            set_cookie(response, cookie_name, cookie_value, cookie_expires)
        return response
    settings.use_editable()
    context = {"blog_post": blog_post, "blog_page": blog_page(),
               "use_disqus": bool(settings.COMMENTS_DISQUS_SHORTNAME),
               "posted_comment_form": posted_comment_form,
               "unposted_comment_form": unposted_comment_form}
    request_context = RequestContext(request, context)
    t = select_template(["blog/%s.html" % slug, template], request_context)
    return HttpResponse(t.render(request_context))