首页 > 解决方案 > 无法将数据传递到模板 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')

任何帮助,将不胜感激。

标签: pythonhtmldjango

解决方案


您不能直接将变量传递给 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>

推荐阅读