Django: how to override CSRF_FAILURE_TEMPLATE

If csrf validation fails, Django displays a 403 error page.

Error page displayed on csrf error

It seems to me that this error can occur with regular use, for example, when a user disables the use of cookies in their browser settings.

Unfortunately, this error message is not very useful for the end user and has a django-error layout (this is a problem because, for example, there is no navigation on the site).

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

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

+6
source share
1 answer

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

 CSRF_FAILURE_VIEW = 'your_app_name.views.csrf_failure' 

In addition, you will need to define the csrf_failure function in your view (you must 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 own template as:

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> {{ message }} </body> </html> 
+11
source

Source: https://habr.com/ru/post/978177/


All Articles