Python 如何在django模板中呈现变量?
我的目标是在HTML页面中动态地编写一些图像的URL。URL存储在数据库中 为此,首先我尝试在模板中呈现一个简单的变量。阅读文档和其他来源,应分三步进行: 对于配置:在settings.py中Python 如何在django模板中呈现变量?,python,django,django-templates,django-views,Python,Django,Django Templates,Django Views,我的目标是在HTML页面中动态地编写一些图像的URL。URL存储在数据库中 为此,首先我尝试在模板中呈现一个简单的变量。阅读文档和其他来源,应分三步进行: 对于配置:在settings.py中 TEMPLATES = [ { 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ … 'django.template.context_processors.re
TEMPLATES = [
{
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
…
'django.template.context_processors.request',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages', ],
},
},
]
模板中的变量名:in MyHTMLFile.html是foo
…
<td>MyLabel</td><td><p>{{ foo }}</p></td><td>-----------</td>
…
html页面呈现良好,但html表中没有数据
你有什么想法吗?我很想知道我误解了什么
关于版本,我使用的是:
python:python 2.7.13
django:1.10.5
多谢各位
context = {foo: myvar1,}
这会给您一个namererror
,当然,除非您有一个名为foo
的变量,在这种情况下,它可能包含字符串foo
。因此,简而言之,您没有向模板发送正确的数据。应该是
context = {'foo': myvar1,}
然后
return render_to_response("MyHTMLFile.html", context, context_instance = RequestContext(request) )
# Below this line code will not be executed.
return render(request, 'MyHTMLFile.html', {foo: myvar1})
return render_to_response("MyHTMLFile.html", context , context_instance=RequestContext(request) )
return render(request, 'MyHTMLFile.html', context)
请注意,return
关键字从函数返回。之后的代码不会被执行
最后,不推荐使用render_to_响应<代码>渲染是当前要使用的函数。谢谢。你的两句话很中肯,我更正了我的代码。我解决了我的问题,因为多亏了你,我意识到我做的测试很糟糕。所以做正确的测试和你的2个代码调整它的工作如预期。我试图向上投票…但有一条红色的消息“你可以在3分钟内接受答案”:-)啊,现在担心了。祝你的项目一切顺利
return render_to_response("MyHTMLFile.html", context, context_instance = RequestContext(request) )
# Below this line code will not be executed.
return render(request, 'MyHTMLFile.html', {foo: myvar1})
return render_to_response("MyHTMLFile.html", context , context_instance=RequestContext(request) )
return render(request, 'MyHTMLFile.html', context)