Django基础之CBV和FBV

我们之前写过的是基于函数的view,就叫FBV。还可以把view写成基于类的。

1. FBV版

def add_class(request):
    if request.method == "POST":
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class/")
    return render(request, "add_class.html")

2. CBV版

基于反射,实现根据请求方式不同,执行不同的方法。
原理:
(1)路由:url---> view函数---->dispatch方法(根据反射执行其他method方法)

from django.views import View
from django.shortcuts import render, HttpResponse, redirect
class AddName(View):
    def get(self, request):
        return render(request, "add_class.html")

    def post(self, request):
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class/")

使用CBV时要注意,请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等再做一些操作的时候,这里我们可以手动改写dispatch方法,这个dispatch方法就和在FBV上加装饰器的效果一样。

from django.vies import View
from django.shortcuts import render, HttpResponse, redirect

class Login(View):

    def dispatch(self, request, *args, **kwargs):
        print("before")
        obj = super(Login, self).dispatch(request, *args, **kwargs)
        print("after")
        return obj

    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        print(request.POST.get("user"))
        return HttpResponse("Login.post")

注意,在使用CBV时,urls.py中也做对应的修改。

url(r"^add_class/$", views.AddClass.as_view())

猜你喜欢

转载自www.cnblogs.com/yang-wei/p/9997671.html
今日推荐