Django : How to override the CSRF_FAILURE_TEMPLATE

五迷三道 提交于 2019-11-29 17:10:38

问题


If csrf checking fails, Django display a page with 403 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?


回答1:


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>



回答2:


As of Django 1.10, you can simply add and customize the 403_csrf.html template: https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-CSRF_FAILURE_VIEW




回答3:


Add 403_csrf.html template to the project template directory.

As you can see in the source code django/views/csrf.py: if you have this template, it will be applied. Nothing needs to be configured.

Template content that you need to customize for your needs:

<div id="summary">
  <h1>{{ title }} <span>(403)</span></h1>
  <p>{{ main }}</p>
{% if no_referer %}
  <p>{{ no_referer1 }}</p>
  <p>{{ no_referer2 }}</p>
  <p>{{ no_referer3 }}</p>
{% endif %}
{% if no_cookie %}
  <p>{{ no_cookie1 }}</p>
  <p>{{ no_cookie2 }}</p>
{% endif %}
</div>


来源:https://stackoverflow.com/questions/26925244/django-how-to-override-the-csrf-failure-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!