【问题标题】:Global variable doesn't work inside django views全局变量在 django 视图中不起作用
【发布时间】:2021-01-04 21:42:43
【问题描述】:

我想在我的 django 视图中使用一些虚拟数据来处理模板。当帖子变量在主函数之外时,我得到的只是空体。虽然当我把它移到里面时,一切都会显示出来。

from django.shortcuts import render
posts = [
    {
        'author': 'Kamil', 
        'title' : 'Post 1',
        
    }, 
    {
        'author': 'Tomek', 
        'title' : 'Post 2',
    }, 
]

def home(request):
    context = {
        'posts' : posts
    }
    return render(request, 'blog_app/home.html', context)

这也是我的html

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>

    <body>
        {% for post in posts %}
            <h1>{{ post.title }}</h1>
            <p>By {{ post.author }}</p>
        {% endfor %}
    </body>
</html>

【问题讨论】:

    标签: python html django django-templates


    【解决方案1】:

    将帖子设为全局变量

    global posts
    
    posts = [
        {
            'author': 'Kamil', 
            'title' : 'Post 1',
            
        }, 
        {
            'author': 'Tomek', 
            'title' : 'Post 2',
        }, 
    ]
    

    【讨论】:

    • 它抛出 SyntaxError: invalid syntax
    • 对不起!我已经更新了我的答案,请检查。全局变量不能同时声明和定义。它们应该分别声明和定义。
    • 天哪,我没有意识到我在这个文件中有同名的函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2017-05-20
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多