Django : How to override the CSRF_FAILURE_TEMPLATE

前端 未结 3 1274
失恋的感觉
失恋的感觉 2020-12-31 05:17

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

\"Error

It

相关标签:
3条回答
  • 2020-12-31 05:27

    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>
    
    0 讨论(0)
  • 2020-12-31 05:36

    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

    0 讨论(0)
  • 2020-12-31 05:47

    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>
    
    0 讨论(0)
提交回复
热议问题