【问题标题】:How to render a variable in a django template?如何在 django 模板中呈现变量?
【发布时间】:2017-11-08 23:49:17
【问题描述】:

我的目标是在 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 2.7.13 django: 1.10.5

谢谢

【问题讨论】:

    标签: python django django-templates django-views


    【解决方案1】:
    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 是当前要使用的函数。

    【讨论】:

    • 谢谢e4c5。您的 2 条评论是相关的,我更正了我的代码。我解决了我的问题,因为多亏了你,我意识到我做的测试很糟糕。所以做正确的测试和你的 2 代码调整它按预期工作。
    • 我尝试投票...但有一条红色消息“您可以在 3 分钟内接受答案”:-)
    • 啊,现在很担心。祝您的项目一切顺利
    猜你喜欢
    • 2021-08-17
    • 2012-12-11
    • 2021-07-16
    • 2021-09-24
    • 2021-01-25
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多