python - Django View 变量未在 html 中显示任何数据

标签 python django django-templates

我正在尝试传递“Hello World!”从 Django View 到 index.html

view.py(请原谅简洁):

def index(request):
    context = "Hello World!"
    return render(request, 'hud/index.html', {"context": context})

index.html(简洁):

<html>
    <h1>{{ index.context }}</h1>
</html>

我期望它打印“context”的值,但它没有。我没有收到任何错误,只是出现空白屏幕。在 chrome 页面源代码中,我看到:

<html>
    <h1></h1>
</html>

感谢任何帮助,我是新人!

最佳答案

你可以这样尝试吗?

在Python中:

def index(request):
    context = "Temp = {0} *C".format(sensor.read_temperature)
    return render(request, 'hud/index.html', {"context": context})

在模板中:

<h1>{{ context }}</h1>

你应该发送带有字典的变量 {"context": context} 是我们的字典。在Django模板中,数据是通过key传递的,所以我们可以通过{{ context }}来获取它。您必须传递一个对象才能使用 doted (index.context) 语法来获取。

关于python - Django View 变量未在 html 中显示任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29955783/

相关文章:

python - 如何从外部访问本地 Django 网络服务器

python - PyQt:多个 QProcess 和输出

python - 有没有办法在字典的键值对中包含用户输入提示或 time.sleep() 函数?

javascript - Django : Is it a good idea to generate JS dynamically?

django - 为django设计模型结构

javascript - 这是否存在 : HTML Template Renderer Written in JavaScript?

django 如何从模板中重定向到主页

django - 向 django 项目中的所有模板提供当前用户

python - setattr() 未设置

python - 类型错误 : Missing 1 required positional argument: 'self'