comments.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. from django import http
  2. from django.conf import settings
  3. from utils import next_redirect, confirmation_view
  4. from django.core.exceptions import ObjectDoesNotExist
  5. from django.db import models
  6. from django.shortcuts import render_to_response
  7. from django.template import RequestContext
  8. from django.template.loader import render_to_string
  9. from django.utils.html import escape
  10. from django.views.decorators.http import require_POST
  11. from django.contrib import comments
  12. from django.contrib.comments import signals
  13. from django.contrib.csrf.decorators import csrf_protect
  14. class CommentPostBadRequest(http.HttpResponseBadRequest):
  15. """
  16. Response returned when a comment post is invalid. If ``DEBUG`` is on a
  17. nice-ish error message will be displayed (for debugging purposes), but in
  18. production mode a simple opaque 400 page will be displayed.
  19. """
  20. def __init__(self, why):
  21. super(CommentPostBadRequest, self).__init__()
  22. if settings.DEBUG:
  23. self.content = render_to_string("comments/400-debug.html", {"why": why})
  24. @csrf_protect
  25. @require_POST
  26. def post_comment(request, next=None):
  27. """
  28. Post a comment.
  29. HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
  30. errors a preview template, ``comments/preview.html``, will be rendered.
  31. """
  32. # Fill out some initial data fields from an authenticated user, if present
  33. data = request.POST.copy()
  34. if request.user.is_authenticated():
  35. if not data.get('name', ''):
  36. data["name"] = request.user.get_full_name() or request.user.username
  37. if not data.get('email', ''):
  38. data["email"] = request.user.email
  39. # Check to see if the POST data overrides the view's next argument.
  40. next = data.get("next", next)
  41. # Look up the object we're trying to comment about
  42. ctype = data.get("content_type")
  43. object_pk = data.get("object_pk")
  44. if ctype is None or object_pk is None:
  45. return CommentPostBadRequest("Missing content_type or object_pk field.")
  46. try:
  47. model = models.get_model(*ctype.split(".", 1))
  48. target = model._default_manager.get(pk=object_pk)
  49. except TypeError:
  50. return CommentPostBadRequest(
  51. "Invalid content_type value: %r" % escape(ctype))
  52. except AttributeError:
  53. return CommentPostBadRequest(
  54. "The given content-type %r does not resolve to a valid model." % \
  55. escape(ctype))
  56. except ObjectDoesNotExist:
  57. return CommentPostBadRequest(
  58. "No object matching content-type %r and object PK %r exists." % \
  59. (escape(ctype), escape(object_pk)))
  60. # Do we want to preview the comment?
  61. preview = "preview" in data
  62. # Construct the comment form
  63. form = comments.get_form()(target, data=data)
  64. # Check security information
  65. if form.security_errors():
  66. return CommentPostBadRequest(
  67. "The comment form failed security verification: %s" % \
  68. escape(str(form.security_errors())))
  69. # If there are errors or if we requested a preview show the comment
  70. if form.errors or preview:
  71. template_list = [
  72. "comments/%s_%s_preview.html" % tuple(str(model._meta).split(".")),
  73. "comments/%s_preview.html" % model._meta.app_label,
  74. "comments/preview.html",
  75. ]
  76. return render_to_response(
  77. template_list, {
  78. "comment" : form.data.get("comment", ""),
  79. "form" : form,
  80. "next": next,
  81. },
  82. RequestContext(request, {})
  83. )
  84. # Otherwise create the comment
  85. comment = form.get_comment_object()
  86. comment.ip_address = request.META.get("REMOTE_ADDR", None)
  87. if request.user.is_authenticated():
  88. comment.user = request.user
  89. # Signal that the comment is about to be saved
  90. responses = signals.comment_will_be_posted.send(
  91. sender = comment.__class__,
  92. comment = comment,
  93. request = request
  94. )
  95. for (receiver, response) in responses:
  96. if response == False:
  97. return CommentPostBadRequest(
  98. "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)
  99. # Save the comment and signal that it was saved
  100. comment.save()
  101. signals.comment_was_posted.send(
  102. sender = comment.__class__,
  103. comment = comment,
  104. request = request
  105. )
  106. return next_redirect(data, next, comment_done, c=comment._get_pk_val())
  107. comment_done = confirmation_view(
  108. template = "comments/posted.html",
  109. doc = """Display a "comment was posted" success page."""
  110. )