python - 无法将数据传递到模板 html 页面 [Django]
问题描述
我有一个 python django 项目,我只是试图将数据传递给模板,但由于某种原因似乎无法让它工作。我的 views.py 文件位于 myproject/mystuff/views.py 中,如下所示:
from django.shortcuts import render
def index(request):
return HttpResponse("TESTING")
def myview(request):
tempData = {'firstname': 'bob','lastname': 'jones'}
weather = "sunny"
data = {
'person': tempData,
'weather': weather
}
return render(request,'myproject/templates/myview.html',data)
在 myview.html 页面中,我只是添加了
<h1>Hi {{ person.firstname }} {{ person.lastname }}</h1>
<h1>Today it is {{ weather }}</h1>
我位于 myproject/mystuff/urls.py 中的 urls.py 如下所示:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.myview, name='myview'),
]
最后,我还有一个用于 django rest 框架的第二个 urls.py ,其中包含一个 urlpatterns[] :
url(r'^myview$', TemplateView.as_view(template_name='myview.html'), name='home')
任何帮助,将不胜感激。
解决方案
您不能直接将变量传递给 html,您需要指定为字典
Django 视图.py
from django.shortcuts import render
def index(request):
return HttpResponse("TESTING")
def myview(request):
tempData = {'firstname': 'bob','lastname': 'jones'}
weather = "sunny"
data = {
'person': tempData,
'weather': weather
}
return render(request,'myproject/templates/myview.html',{'data':data})
#passing value in a dictionary
在 Html 页面中,我们可以访问值字典键值
<h1>Hi {{ data.person.firstname }} {{ person.lastname }}</h1>
<h1>Today it is {{ data.weather }}</h1>
推荐阅读
- python - 在 Django UpdateView 中覆盖 get() 方法会给出“str”没有属性获取错误
- angular - 反应形式的总和数组
- vba - 如何搜索字符串并突出显示相邻的单词?
- java - Netbeans Maven 项目中 ResourceBundle 的 Bundle 类路径无效
- arrays - 列表中总和的练习
- javascript - 动态插入到 DOM 后,样式不会应用于 HTML 元素 - Angular
- android - 我想要使用 android-studio 在 android 中以某个数字开头的按钮的代码
- pandas - 使用多个键转换熊猫数据框
- animation - 如何在 adobe animate 2021 中扭曲视频?
- c - C 调用具有空声明 arglist 的函数,使用 args 定义