【问题标题】:Django 1.8 csrf NameError: UndefinedDjango 1.8 csrf NameError:未定义
【发布时间】:2018-03-15 07:33:37
【问题描述】:

我在 Django 之上使用 Django_Mako_Plus。当我尝试在我的表格后面加上${csrf_input} 时。我收到了NameError: Undefined。中间件是正确的。我究竟做错了什么?以下是我的代码:

<div class="backgroundregister">
    <form id="registerform" action="/homepage/register" method="post" style="margin-top: -7vh;">${csrf_input}

        <div class="form-group" id="register-id">

            ${ form.as_table() }

            <button style="margin-top:15px; height:40px; width:300px; margin-left:3px; margin-top:30px;" type="submit" class="dissimulation">
        </div>


    </form>

</div>

我正在使用 Django 1.8

提前感谢您的所有帮助。

【问题讨论】:

  • Django marko plus 支持 django >= 1.9 ,为什么不用 django 1.11 代替 1.8 呢?
  • @Beomi 我相信 django 1.9 的更新破坏了 1.8 的内容。至少对我的网站有用。
  • 发布你的 settings.py
  • 你试过 ${csrf_input} 用空格代替: ${ csrf_input }。
  • 作为更新,我做了一些工作并升级到 1.9,修复了所有问题,但我仍然收到错误。

标签: python django csrf django-1.8


【解决方案1】:

https://pypi.python.org/pypi/django-mako-plus/3.8.3 下载 Django-mako-plus 3.8.3 并检查源代码后,我发现context_processors.py 没有任何csrf 函数的定义。不过这个函数是定义在https://pypi.python.org/pypi/django-mako-plus/4.2.6

AFAIK,中间件没有为 csrf 注册上下文处理器。

这些必须添加到您的项目设置中的CONTEXT_PROCESSORS

对于旧版本的django-mako-plus,请在您的应用目录中创建一个context_processors.py 模块,其中包含从源代码中厚颜无耻地复制的此功能:

from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy

def csrf(request):
    '''
    Adds the "csrf_input" and "csrf_token" variables to the request.
    Following Django's lead, this processor is included in DMP's
    default context processors list. It does not need to be listed
    in settings.py.
    To include the <input name="csrf".../> control in your forms,
    use ${ csrf_input }.
    '''
    return {
        'csrf_input': csrf_input_lazy(request),
        'csrf_token': csrf_token_lazy(request),
    }

在您的settings.py 中使用此模块的位置。

TEMPLATES = [
    {
        'NAME': 'django_mako_plus',
        'BACKEND': 'django_mako_plus.MakoTemplates',
        'OPTIONS': {
            # functions to automatically add variables to the params/context before templates are rendered
            'CONTEXT_PROCESSORS': [
                 ...
                 # adds "settings" dictionary
                'django_mako_plus.context_processors.settings',
                 # adds "csrf" dictionary
                '<appname>.context_processors.csrf',
            ],

参考

(django-mako-plus 4.2.6)django_mako_plus.context_processors.csrf_input

【讨论】:

  • 我已经将这些添加到我的 context_processors 中。我仍然遇到同样的错误。
  • 你运行的是什么版本的 django_mako_plus?
  • 我正在运行 django-mako-plus 3.3.18.0
  • 我是否只需创建一个新的 py 文件,其中包含名为 context_processors.py 的其余视图?还是我会把它放在我的 base.py 文件中?
  • 没关系,看起来您的解决方案有效。我只是在验证,但如果它有效,我会把分数分配给你。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 2023-01-17
  • 2018-07-14
  • 2017-12-25
  • 2021-07-17
  • 2012-05-13
  • 2017-08-17
相关资源
最近更新 更多