# 4-1 构建网页内容
# 视图函数return的响应类型
# HttpResponse('Hello World') HTTP状态码200,请求已成功被服务器接收
# HttpResponseRedirect('/admin/') HTTP状态码302,重定向Admin站点的URL
# HttpResponsePermanentRedirect('/admin/) HTTP状态码301,永久重定向Admin站点的URL
# HttpResponseBadRequest('BadRequest') HTTP状态码400,访问的页面不存在或者请求错误
# HttpResponseNotFound('NotFound') HTTP状态码404,网页不存在或网页的URL失效
# HttpResponseForbidden('NotFound') HTTP状态码403,没有访问权限
# HttpResponseNotAllowed('NotAllowedGet') HTTP状态码405,不允许使用该请求方式
# HttpResponseServerError('ServerError') HTTP状态码500,服务器内容错误
# 在实际开发中,可以使用该模板实现文件下载功能,在index的urls.py和views.py中分别添加以下代码:
# urls.py代码
path('download', views.download),
# views.py代码
def download(request):
# 当接收到用户的请求后,视图函数download首先定义HttpResponse的相应类型为文件(text/csv)类型,生成response对象
response = HttpResponse(content_type='text/csv')
# 然后在response对象上定力Content-Disposition,设置浏览器下载文件的名称
# attachment设置文件下载的方式,filename为文件名
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
# 最后使用CSV模块加载response对象,把数据写入response对象所设置的CSV文件并将response对象返回到浏览器上,从而实现文件下载。
writer = csv.writer(response)
writer.writerow(['First row', 'A', 'B', 'C'])
return response
# render的语法如下:
def render(request, template_name, context=None, content_type=None, status=None, using=None):
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
# request:浏览器向服务器发送的请求对象,包括用户信息、请求内容和请求方式等
# template_name:HTML模板文件名,用于生成HTML网页
# context:对HTML模板的变量赋值,以字典格式表示,默认情况下是一个空字典
# content_type:响应数据的数据格式,一般情况下使用默认值即可
# status:HTTP状态码,默认为200
# using:设置HTML模板转换生成HTML网页的模板引擎
# 项目的templates有index.html模板,这是一个伪华为商城的网页,static用于存放该HTML模板的静态资源,
# urls.py代码如下:
path('',views.index),
#views.py代码如下:
def index(request):
return render(request,'index.html',context={'title':'首页'},status=500)
# 除了render函数外,还有redirect函数:
# urls.py的URL地址信息:
path('login.html',views.login)
# views.py的视图函数:
def login(request):
return redirect('/') #相对路径
return redirect('http://127.0.0.1:8000/') #绝对路径
4-2 数据可视化
# 视图除了接收用户请求和返回响应内容外,还可以与模型(Model)实现数据交互(操作数据库)。
# 视图相当于一个处理中心,负责接收用户请求,然后根据请求信息读取并处理后台数据,最后生成HTML网页返回给用户。
# 视图操作数据库实质是从models.py导入数据库映射对象,models.py的数据库对象是通过Django内置的ORM框架构建数据库映射的,从而生成数据库对象。
# 下面代码将Product类和数据表Product构成映射关系,代码只是搭建两者的关系,在数据库中并没有生成相应的数据表
# Python manage.py makemigrations
# python manage.py migrate
from django.db import models
class Product(models.Model):
id=models.IntegerField(primary_key=True)
name=models.CharField(max_length=50)
type=models.CharField(max_length=20)
# 首先将模板文件index.html左侧导航栏的代码注释掉,然后在同一位置添加Django的模板语法,代码如下:
<ul id="cate_box" class="lf">
{% for type in type_list %}
<li>
<h3><a href="#">{{ type.type }}</a></h3>
<p>
{% for name in name_list %}
{% if name.type == type.type %}
<span>{{ name.name }}</span>
{% endif %}
{% endfor %}
</p>
</li>
{% endfor %}
</ul>
# 最后在视图函数中编写代码,将数据表的数据与模板连接起来,首先数据可视化,代码如下:
def index(request):
# type_list用于查询数据表字段type的数据并将数据去重
type_list = Product.objects.values('type').distinct()
# name_list用于查询数据字段type和name的全部数据
name_list = Product.objects.values('name','type')
# 将查询所得的数据以字典的数据格式写入变量context中,变量context是render()函数的参数值,其作用是将变量传递给HTML模板
context = {'title': '首页', 'type_list': type_list, 'name_list': name_list}
# 当HTML模板接收到变量type_list和name_list后,模板引擎解析模板语法并生成HTML文件
return render(request, 'index.html',context=context, status=200)
4-3 获取请求信息
# 我们知道视图是用于接收并处理用户信息的请求信息,请求信息存放在视图函数的参数request中。
# request的常用属性
# COOKIES 获取客户端(浏览器)Cookie信息 data=request.COOKIES
# FILES 字典对象,包含所有的上载文件。该字典有三个键:
# filename为上传文件的文件名;content_type为上传文件的额类型;content为上传文件的原始内容 file=request.FILES
# GET 获取GET请求的请求参数,以字典形式存储 //如{'name':'TOM'} request.GET.get('name')
# META 获取客户端的请求头信息,以字典形式存储 //获取客户端的IP地址 request.META.get('REMOTE_ADDR')
# POST 获取POST请求的请求参数,以字典形式存储 //如{'name':'TOM'} request.POST.get('name')
# method 获取给请求的请求方式(GET或POST请求) data=request.method
# path 获取当前请求的URL地址 path=request.path
# user 获取当前请求的用户信息 //获取用户名 name=request.user.username
# 以视图函数login为例,代码如下:
# urls.py
from django.urls import path
from . import views
urlpatterns=[
path('login.html',views,login),
]
# views.py
def login(resquest):
if request,method=='POST':
name=request.POST.get('name')
# return redirect('http://127.0.0.1:8000/')
return redirect('/')
else:
if request.GET.get('name'):
name=request.GET.get('name')
else:
name='Everyone
return HttpResponse('username is ' +name)
# 在浏览器上分别输入以下URL地址:
http://127.0.0.1:8000/login
http://127.0.0.1:8000/login?name=Tom
# 一般情况下,在网页上输入信息并点击某个按钮时,以POST请求居多,如用户登录、注册等
# 若判断请求方式为POST(GET),则通过属性POST(GET)来获取用户提交的请求参数。
4-4 通用视图
# 通用视图是通过定义和生命类的形式实现的,根据用途划分为三大类:TemplateView、ListView和DetailView。
# templateView:直接返回HTML模板,但无法将数据库的数据展示出来
# ListView:能将数据库的数据传递给HTML模板,通常获取某个表的所有数据
# DetailView:能将数据库的数据传递给HTML模板,通常获取数据表的单条数据
# 根据4.2节实现的功能,将其试图函数改用ListView实现。
# urls.py代码
from django.urls import path
from . import views
urlpatterns=[
path('index/',views.ProductList.as_view())