1.什么是视图层
简单来说,就是用来接收路由层传来的请求,从而做出相应的响应返回给浏览器
2.视图层的格式与参数说明
2.1基本格式
- from django.http import HttpResponse
- def page_2003(request):
- html = '<h1>第一个网页</h1>'
- return HttpResponse(html)
- # 注意需要在主路由文件中引入新创建的视图函数
复制代码 2.2带有转换器参数的视图函数
- def test(request, num):
- html = '这是我的第%s个网页' % num
- return HttpResponse(html)
- # 添加转换器的视图函数,request后面的参数num为path转换器中的自定义名
复制代码 2.3带有正则表达式参数的视图函数
同带有转换器参数的视图函数
2.4重定向的视图函数
- from django.http import HttpResponse,HttpResponseRedirect
- def test_request(request):--注意path函数里也要绑定test_request这个路径
- return HttpResponseRedirect('page/2003/')--重定向到127.0.0.1:8000/page/2003这个页面去
复制代码 2.5判断请求方法的视图函数
- def test_get_post(request):
- if request.method == 'GET':
- pass
- elif request.method == 'POST':
- pass
复制代码 2.6加载模板层的视图函数
- 使用render()直接加载并相应模板语法:
- from django.shortcuts import render
- def test_html(request):
- return render(request, '模板文件名', 字典数据)
- 注意视图层的所有变量可以用local()方法全部自动整合成字典传到render的最后一个参数里
复制代码 2.7返回JsonResponse对象的视图函数
json格式的数据的作用:
前后端数据交互需要用到json作为过渡,实现跨语言传输数据。
格式:- from django.http import JsonResponse
- def ab_json(request):
- user_dict={'username':'json,我好喜欢','password':'1243'}
- return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})
- # 字典传入时需要设置json_dumps_params格式化字符串,不然字典里的中文会报错
- list = [111,22,33,44]
- return JsonResponse(list,safe=False)
- # 列表传入序列化时需要设置safe为false ,不然会报错
复制代码 2.8视图层的FBV和CBV格式
视图函数既可以是函数(FBV)也可以是类(CBV)- 1.FBV
- def index(request):
- return HttpResponse('index')
- 2.CBV
- # CBV路由
- pathr'^login/',views.MyLogin.as_view())
- # CBV视图函数
- from django.views import View
- class MyLogin(View):
- def get(self,request):
- return render(request,'form.html')
- def post(self,request):
- return HttpResponse('post方法')
- """
- FBV和CBV各有千秋
- CBV特点
- 能够直接根据请求方式的不同直接匹配到对应的方法执行
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |