我在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
提前感谢您的帮助。
答案 0 :(得分: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
,请在app目录中创建一个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