我们将在 myapp 创建一个简单的视图显示: "welcome to h3 !"
查看如下的视图 −
from django.http import httpresponse def hello(request): text = """<h1>welcome to h3 !</h1>""" return httpresponse(text)
在这个视图中,我们使用 httpresponse 呈现 html(你可能已经注意到了,我们将html硬编码在视图中)。 在这个视图我们只是需要把它映射到一个url(这将在即将到来的章节中讨论)的页面。
我们使用 httpresponse 在渲染视图 html 之前。 这不是渲染网页的最佳方式。django支持mvt模式,从而先渲染视图,django - mvt这是我们需要的−
一个模板文件: myapp/templates/hello.html
现在,我们的视图内容如下 −
from django.shortcuts import render def hello(request): return render(request, "myapp/template/hello.html", {})
from django.http import httpresponse def hello(request, number): text = "<h1>welcome to my app number %s!</h1>"% number return httpresponse(text)
当链接到一个网址,页面会显示作为参数传递的数值。 注意,参数将通过url(在下一章节中讨论)传递。