views.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from django import http
  2. from django.conf import settings
  3. from django.template import loader
  4. from django.utils import decorators
  5. from django.views.decorators import csrf
  6. class EnsureCsrfCookieMixin(object):
  7. """
  8. Mixin for Django class-based views which forces a view to send the CSRF cookie.
  9. This is useful when using Ajax-based sites which do not have an HTML form with
  10. a :tag:`csrf_token` that would cause the required CSRF cookie to be sent.
  11. """
  12. @decorators.method_decorator(csrf.ensure_csrf_cookie)
  13. def dispatch(self, *args, **kwargs):
  14. return super(EnsureCsrfCookieMixin, self).dispatch(*args, **kwargs)
  15. def bad_request_view(request, exception=None):
  16. """
  17. Displays 400 bad request page.
  18. It is similar to the Django built-in ``django.views.defaults.permission_denied`` view,
  19. but always uses a template and a request context.
  20. You can configure Django to use this view by adding to ``urls.py``::
  21. handler400 = 'missing.views.bad_request_view'
  22. Template should not require a CSRF token.
  23. """
  24. t = loader.get_template('400.html')
  25. return http.HttpResponseBadRequest(t.render(request=request, context={
  26. 'DEBUG': settings.DEBUG,
  27. 'exception': str(exception) if exception else None,
  28. }), content_type='text/html')
  29. def forbidden_view(request, exception=None, reason=''):
  30. """
  31. Displays 403 forbidden page. For example, when request fails CSRF protection.
  32. It is similar to a merged Django built-in ``django.views.defaults.permission_denied`` and
  33. ``django.views.csrf.csrf_failure`` views, but always uses a template and a request context.
  34. You can configure Django to use this view by adding to ``urls.py``::
  35. handler403 = 'missing.views.forbidden_view'
  36. and to ``settings.py``::
  37. CSRF_FAILURE_VIEW = 'missing.views.forbidden_view'
  38. Template should not require a CSRF token.
  39. """
  40. from django.middleware import csrf
  41. t = loader.get_template('403.html')
  42. return http.HttpResponseForbidden(t.render(request=request, context={
  43. 'DEBUG': settings.DEBUG,
  44. 'reason': reason,
  45. 'no_referer': reason == csrf.REASON_NO_REFERER,
  46. 'no_cookie': reason == csrf.REASON_NO_CSRF_COOKIE,
  47. 'exception': str(exception) if exception else None,
  48. }), content_type='text/html')