一、FBV
FBV(function base views) 就是在视图里使用函数处理请求,也是我们最开始接触和使用的方式。
urls.py
urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^login/$‘, account.login), ]
views.py
# 登录验证 def login(request): message = "" if request.method == "POST": user = request.POST.get(‘username‘) pwd = request.POST.get(‘password‘) c = Administrator.objects.filter(username=user, password=pwd).count() if c: request.session[‘is_login‘] = True request.session[‘username‘] = user return redirect(‘/index.html‘) else: message = "用户名或密码错误" return render(request, ‘login.html‘, {‘msg‘: message})
说白了,FBV就是在views.py文件中定义函数来处理用户请求,函数中再定义如果是GET请求怎么处理,POST请求怎么处理,等等!
二、CBV
CBV(class base views) 就是在视图里使用类处理请求。
urls.py
urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^login/$‘, account.Login.as_view()), ]
views.py
from django import views from django.utils.decorators import method_decorator class Login(views.View): def get(self, request, *args, **kwagrs): return render(request, ‘login.html‘) def post(self, request, *args, **kwagrs): user = request.POST.get(‘username‘) pwd = request.POST.get(‘password‘) c = Administrator.objects.filter(username=user, password=pwd).count() if c: request.session[‘is_login‘] = True request.session[‘username‘] = user return redirect(‘/index.html‘) else: message = "用户名或密码错误" return render(request, ‘login.html‘, {‘msg‘: message})
当我们使用CBV方式时,首先要注意urls.py文件中要写成“类名.as_view()”方式映射,其次在类中我们定义的get/post方法这些方法的名字不是我们自己定义的,而是按照固定样式,View类中支持以下方法:
http_method_names = [‘get‘, ‘post‘, ‘put‘, ‘patch‘, ‘delete‘, ‘head‘, ‘options‘, ‘trace‘]
当我们发送GET请求时,类自动将GET请求转到get方法去处理,其他请求同理!
本文出自 “戴柏阳的博客” 博客,请务必保留此出处http://daibaiyang119.blog.51cto.com/3145591/1976717
原文地址:http://daibaiyang119.blog.51cto.com/3145591/1976717