Django教程

Django创建视图

Django创建视图详细操作教程
视图功能,或简称"view",是一个简单的Python函数,它接受一个Web请求,并返回一个Web响应。此响应可以是 Web页的HTML内容,或重定向,或404错误,或XML文档,或图像/片等。例如:使用视图创建页面,请注意需要将一个视图关联到一个URL,并把它看作一个网页。
在Django中,视图必须在应用程序的 views.py 文件中创建。

简单的视图

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