Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : How to override the CSRF_FAILURE_TEMPLATE

If csrf checking fails, Django display a page with 403 error.

Error page displayed on csrf error

It seems to me that this error can occur in regular use, for example, when the user disable cookie usage in his browser settings.

Unfortunately, this error message is not very helpful for the end-user and has a "django-error" layout (this is a problem because for example the site navigation is missing).

Django has a great mechanism for overriding templates but it seems that this template is hard-coded in the code. https://github.com/django/django/blob/1.6.8/django/views/csrf.py

Is there a way to override this template in order to provide a more friendly message to users?

like image 652
luc Avatar asked Nov 14 '14 07:11

luc


1 Answers

Refer to the Django document, you can set CSRF_FAILURE_VIEW in your settings.py, such as:

CSRF_FAILURE_VIEW = 'your_app_name.views.csrf_failure'

Also, you'll need to define a csrf_failure function in your view (need to have this signature: def csrf_failure(request, reason="") based on the document), which is similar to :

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

And you can write your custom template as:

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        {{ message }}
    </body>
</html>
like image 55
dazedconfused Avatar answered Oct 01 '22 22:10

dazedconfused