utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. A few bits of helper functions for comment views.
  3. """
  4. import textwrap
  5. from django.http import HttpResponseRedirect
  6. from django.shortcuts import render_to_response, resolve_url
  7. from django.template import RequestContext
  8. from django.core.exceptions import ObjectDoesNotExist
  9. from django.contrib import comments
  10. from django.utils.http import is_safe_url
  11. from django.utils.six.moves.urllib.parse import urlencode
  12. def next_redirect(request, fallback, **get_kwargs):
  13. """
  14. Handle the "where should I go next?" part of comment views.
  15. The next value could be a
  16. ``?next=...`` GET arg or the URL of a given view (``fallback``). See
  17. the view modules for examples.
  18. Returns an ``HttpResponseRedirect``.
  19. """
  20. next = request.POST.get('next')
  21. if not is_safe_url(url=next, host=request.get_host()):
  22. next = resolve_url(fallback)
  23. if get_kwargs:
  24. if '#' in next:
  25. tmp = next.rsplit('#', 1)
  26. next = tmp[0]
  27. anchor = '#' + tmp[1]
  28. else:
  29. anchor = ''
  30. joiner = '&' if '?' in next else '?'
  31. next += joiner + urlencode(get_kwargs) + anchor
  32. return HttpResponseRedirect(next)
  33. def confirmation_view(template, doc="Display a confirmation view."):
  34. """
  35. Confirmation view generator for the "comment was
  36. posted/flagged/deleted/approved" views.
  37. """
  38. def confirmed(request):
  39. comment = None
  40. if 'c' in request.GET:
  41. try:
  42. comment = comments.get_model().objects.get(pk=request.GET['c'])
  43. except (ObjectDoesNotExist, ValueError):
  44. pass
  45. return render_to_response(template,
  46. {'comment': comment},
  47. context_instance=RequestContext(request)
  48. )
  49. confirmed.__doc__ = textwrap.dedent("""\
  50. %s
  51. Templates: :template:`%s``
  52. Context:
  53. comment
  54. The posted comment
  55. """ % (doc, template)
  56. )
  57. return confirmed