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