views.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from django.http import HttpResponseForbidden
  2. from django.template import Context, Template
  3. from django.conf import settings
  4. # We include the template inline since we need to be able to reliably display
  5. # this error message, especially for the sake of developers, and there isn't any
  6. # other way of making it available independent of what is in the settings file.
  7. CSRF_FAILRE_TEMPLATE = """
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  9. <html lang="en">
  10. <head>
  11. <meta http-equiv="content-type" content="text/html; charset=utf-8">
  12. <title>403 Forbidden</title>
  13. </head>
  14. <body>
  15. <h1>403 Forbidden</h1>
  16. <p>CSRF verification failed. Request aborted.</p>
  17. {% if DEBUG %}
  18. <h2>Help</h2>
  19. {% if reason %}
  20. <p>Reason given for failure:</p>
  21. <pre>
  22. {{ reason }}
  23. </pre>
  24. {% endif %}
  25. <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
  26. <a
  27. href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'>Django's
  28. CSRF mechanism</a> has not been used correctly. For POST forms, you need to
  29. ensure:</p>
  30. <ul>
  31. <li>The view function uses <a
  32. href='http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext'><tt>RequestContext</tt></a>
  33. for the template, instead of <tt>Context</tt>.</li>
  34. <li>In the template, there is a <tt>{% templatetag openblock %} csrf_token
  35. {% templatetag closeblock %}</tt> template tag inside each POST form that
  36. targets an internal URL.</li>
  37. </ul>
  38. <p>You're seeing the help section of this page because you have <code>DEBUG =
  39. True</code> in your Django settings file. Change that to <code>False</code>,
  40. and only the initial error message will be displayed. </p>
  41. <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
  42. {% endif %}
  43. </body>
  44. </html>
  45. """
  46. def csrf_failure(request, reason=""):
  47. """
  48. Default view used when request fails CSRF protection
  49. """
  50. t = Template(CSRF_FAILRE_TEMPLATE)
  51. c = Context({'DEBUG': settings.DEBUG,
  52. 'reason': reason})
  53. return HttpResponseForbidden(t.render(c), mimetype='text/html')