目录:
- FBV与CBV
- ajax序列化补充
- Form表单(一)
一、FBV与CBV
1、什么是FBV、CBV?
django书写view时,支持两种格式写法,FBV(function bases view即函数编程),CBV(class bases view即类编程)。
其中函数编程是本blog一直使用的编程方式,不再讨论。以下主要讨论CBV方式。但这两种方式没有优劣,书写可选择任意一种使用
2、CBV写法应用之登陆验证
1 from django.shortcuts import render,HttpResponse, redirect 2 from django.views import View 3 from django.views.decorators.csrf import csrf_exempt,csrf_protect 4 from django.utils.decorators import method_decorator 5 6 def auth(func): 7 def inner(request,*args,**kwargs): 8 if request.session.get('username'): 9 obj = func(request,*args,**kwargs) 10 return obj 11 else: 12 return redirect('/login.html') 13 return inner 14 15 16 # @method_decorator(auth,name='get') 17 class IndexView(View): 18 19 @method_decorator(auth) 20 def dispatch(self, request, *args, **kwargs): 21 if request.session.get('username'): 22 response = super(IndexView,self).dispatch(request, *args, **kwargs) 23 return response 24 else: 25 return redirect('/login.html') 26 27 @method_decorator(auth) 28 def get(self,request,*args,**kwargs): 29 return HttpResponse(request.session['username']) 30 31 @method_decorator(csrf_exempt) # 无效 32 def post(self,request,*args,**kwargs): 33 return HttpResponse(request.session['username'])