1

我有一个 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')

任何帮助,将不胜感激。

4

2 回答 2

1

您不能直接将变量传递给 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>
于 2019-03-22T04:22:13.840 回答
-1

您传递数据的方式是正确的。

但是,在较新版本的 Django 中,包括您正在使用的 2.1.5,建议使用它path来构建 url 路径。

你在 urls.py 中像这样使用它:

from django.urls import path
from . import views
urlpatterns = [
    path('myview', views.myview, name='myview')
]

展示如何使用路径构建 url 路径的官方教程: https ://docs.djangoproject.com/en/2.1/intro/tutorial01/

官方文档django.urls.pathhttps ://docs.djangoproject.com/en/2.1/ref/urls/

于 2019-03-22T05:25:46.283 回答