python - 如何在 Django 模板中呈现变量?

标签 python django django-templates django-views

我的目标是在 HTML 页面中动态写入一些图像的 url。网址存储在数据库中。

为此,我首先尝试在模板中呈现一个简单的变量。阅读文档和其他资源,应该分 3 个步骤完成:

对于配置:在settings.py

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',            ],
    },
},

]

模板中的变量名在MyHTMLFile.html中是foo

…
<td>MyLabel</td><td><p>{{ foo }}</p></td><td>-----------</td>
…

在 view.py 中,其中一行

myvar1 ="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
context = {foo: myvar1,}

return render_to_response("MyHTMLFile.html", context, context_instance = RequestContext(request) )
return render(request, 'MyHTMLFile.html', {foo: myvar1})
return render_to_response("MyHTMLFile.html", context , context_instance=RequestContext(request) )
return render(request, 'MyHTMLFile.html', context)

html 页面呈现良好,但 html 表中没有数据。

你有想法吗?我很想知道我误解了什么。

关于版本,我使用的是: python : python 2.7.13 Django :1.10.5

谢谢

最佳答案

context = {foo: myvar1,}

这应该给你一个 NameError 除非你当然有一个名为 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_response 被弃用了。 render 是当前要使用的函数。

关于python - 如何在 Django 模板中呈现变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415794/

相关文章:

Heroku、Boto 或 Cloudinary 上的 Django 媒体

django - Django 模板中的搜索字段

django - 如何在 Django 中获取表单字段的 ID

python - 替换 Django 模板中的字符

python - 如何闪烁由flask_socketio发出的消息?

python - 将 Python 函数参数存储为变量以供以后调用

python - 组织大型 Django 项目的指南

python - Django 无法加载测试装置,IntegrityError

python Selenium - 无法获取 Facebook 表格内容

python - pickle 一个动态参数化的子类