【问题标题】:Django: undefined template variable renders as context dumpDjango:未定义的模板变量呈现为上下文转储
【发布时间】:2017-03-13 01:32:47
【问题描述】:

Django 1.10.1

我的模板使用了一个强制的“title”上下文变量和一个可选的“note”模板变量。

渲染 {{ title }} 工作正常,但渲染 {{ note }} 会导致渲染完整的模板上下文(调试视图的种类?)如果在上下文中没有定义 note。

我希望 is 'note' 没有在上下文中定义它会呈现一个空字符串,如果定义会呈现变量的内容。

示例:

urls.py:

url(r'^test1', views.testview1),
url(r'^test2', views.testview2),

views.py:

def testview1(request):
    context = {'title': 'My title', 'note': 'my note'}
    return render(request, 'test_template.html', context)


def testview2(request):
    context = {'title': 'My title'}
    return render(request, 'test_template.html', context)

test_template.html:

<h2>{{ title }}</h2>
{{ note }}

testview1 按预期呈现:

我的标题

我的笔记

testview2 呈现这个意外的上下文转储:

我的标题

[{'False': False, 'None': 无, 'True': True}, {u'csrf_token': , '用户':>, 'perms': , 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'WARNING': 30, 'SUCCESS': 25, 'ERROR': 40}, 'messages': , u'request': }, {}, {'title': 'My title'}]

这是与模板相关的 settings.py 上下文:

DEBUG = True
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'),
                 os.path.join(BASE_DIR, 'templates', 'allauth')],
        'APP_DIRS': True,
        'OPTIONS': {
            'string_if_invalid': '',
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

这些python模块在虚拟环境中:

Babel==2.3.4
BulkSMS==0.3
cGraph==0.1
diff-match-patch==20121119
Django==1.10.1
django-allauth==0.27.0
django-bootstrap-ui==0.2.0
django-bootstrap3==7.0.1
django-crispy-forms==1.6.0
django-debug-toolbar==1.5
django-extensions==1.7.4
django-import-export==0.5.1
django-mailjet==0.2.0
django-phonenumber-field==1.1.0
django-tag-parser==2.1
django-utils==0.0.2
dominate==2.1.17
funcsigs==1.0.2
graphviz==0.5.1
mailjet-rest==1.2.2
MarkupSafe==0.23
mock==2.0.0
nose==1.3.7
oauthlib==2.0.0
pbr==1.10.0
phonenumberslite==7.7.2
pydot2==1.0.33
pygraphviz==1.3.1
pyparsing==2.1.10
python-openid==2.2.5
pytz==2016.7
requests==2.11.1
requests-oauthlib==0.6.2
six==1.10.0
sqlparse==0.2.1
tablib==0.11.2

【问题讨论】:

  • 一个一个禁用所有应用程序,没有一个导致这个问题。当我创建一个新的 django 项目时,这个问题不存在,所以很明显我的项目在某处有一些错误配置......

标签: python django templates


【解决方案1】:

其中一个 python 包发生了本地更改。

所以这解决了这个问题:

pip install -r requirements.txt --ignore-installed

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    相关资源
    最近更新 更多