someone someone - 10 days ago 5
Apache Configuration Question

How to set a default handler for "CSRF verification failed" in django?

According to the Django documentation, we can set the a default error handler like this:

handler403 = 'mysite.views.my_custom_permission_denied_view'
...


My handler for 404 and 500 is working fine. But in case of access forbidden, I can't trigger it (when I raise
HttpResponseForbidden
, the triggered handler is the handler for error 500). Anyway, that's not my problem. My problem is when I try to tamper (for testing purposes) the
CSRF
token, it throws "Forbidden" but again, my handler for access forbidden is not invoked - it invokes the default django template for 403 forbidden. And when I try to access the root directory of
static
(or
media
) directory, the invoked page is from the servers default forbidden page (apache httpd in my case) which is fine.

My question is:


  • How to set default handler for "CSRF verification failed"?

  • What are the cases that the 403 handler is being called?

  • How can I trigger a 403 forbidden error?



Here is my setup:


  • Python 3.4

  • Django 1.10 (production, debug = False)

  • Server: Apache httpd through mod_wsgi

  • Windows 7 32bit


Answer

You can do, in settings

CSRF_FAILURE_VIEW = 'your_app_name.views.csrf_failure'

in view

def csrf_failure(request, reason=""):
    ctx = {'message': 'some custom messages'}
    return render(request, your_custom_template, ctx)
Comments