Django:如何覆盖CSRF_FAILURE_TEMPLATE [英] Django : How to override the CSRF_FAILURE_TEMPLATE

查看:142
本文介绍了Django:如何覆盖CSRF_FAILURE_TEMPLATE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果csrf检查失败,Django将显示403错误的页面。

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

在我看来,这种错误可能会发生在常规使用中,例如,当用户禁用cookie使用在他的浏览器设置中。

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

不幸的是,这个错误消息对最终用户来说不是很有帮助,并且有一个django-error布局(这是一个问题,因为例如,网站导航缺少)。

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有一个很好的机制来覆盖模板,但似乎这个模板在代码中是硬编码的。 https://github.com/django/django/blob /1.6.8/django/views/csrf.py

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?

推荐答案

请参阅 Django文档,您可以在 settings.py中设置 CSRF_FAILURE_VIEW / code>,例如:

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'

此外,您需要在视图中定义一个 csrf_failure 函数需要具有以下签名: def csrf_failure(request,reason =)基于文档),类似于:

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>

这篇关于Django:如何覆盖CSRF_FAILURE_TEMPLATE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆