簡體   English   中英

Django:未定義的模板變量呈現為上下文轉儲

[英]Django: undefined template variable renders as context dump

Django 1.10.1

我的模板使用強制性的“ title”上下文變量和可選的“ note”模板變量。

渲染{{title}}可以很好地工作,但是如果未在上下文中定義note,則渲染{{note}}會導致呈現完整的模板上下文(類似於調試視圖?)。

我希望在上下文中未定義“ 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':None,'True':True},{u'csrf_token':<SimpleLazyObject:u'ho7MGwEQ86eMVLmHZbDPYE8VLCo3aTAUTM0OAf7Pvr5E8exMKYDqNoTjQGmieLPu <>:'User1,用戶: 'perms':<django.contrib.auth.context_processors.PermWrapper對象位於0x113826f50>,'DEFAULT_MESSAGE_LEVELS':{'DEBUG':10,'INFO':20,'WARNING':30,'SUCCESS':25,'ERROR ':40},'messages':<django.contrib.messages.storage.fallback.FallbackStorage對象位於0x11376b550>,u'request':<WSGIRequest:GET'/ swingit / test2'>},{},{'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

其中一個python軟件包進行了局部更改。

所以這解決了這個問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM