Django 學習視圖之FBV與CBV

. CBVFBV

CBVClass Based Viewcss

FBVFunction Based Viewhtml

咱們以前寫過的都是基於函數的view,就叫FBV。還能夠把view寫成基於類的,那就是CBV前端

下面咱們就拿添加用戶爲例:python

1.FBV版本

首先:urls.py 的與視圖關係編寫爲:path('register/', views.register),jquery

而後是視圖函數的內容:ajax

from django.contrib.auth.models import Userdjango

from django.shortcuts import render, HttpResponse, redirectbootstrap

# 註冊及驗證 (前端模板是以ajax實現)app

def register(request):ide

    if request.method == "GET":

        return render(request, "register.html")

    if request.method == "POST":

        username = request.POST.get("username")

        password = request.POST.get("pwd")

        print(username)

        print(password)

        User.objects.create_user(username=username, password=password)  # User是以個對象

        return redirect("/index/")

 

2.CBV版本

首先:urls.py 的與視圖關係編寫爲:path('register/', views.Register.as_view()),

而後是視圖函數類編寫的內容:

from django.views import View

class Register(View):

    def get(self, request):

        return render(request, "register.html")

 

    def post(self, request):

        username = request.POST.get("username")

        password = request.POST.get("pwd")

        print(username)

        print(password)

        User.objects.create_user(username=username, password=password)  

# User是以個對象

        return redirect("/index/")

 

. 給視圖加裝飾器

1. 使用裝飾器裝飾FBV

FBV自己就是一個函數,因此和給普通的函數加裝飾器無差:

# 一個時間的裝飾器來驗證是否運行了裝飾器

def wrapper(func):

    def inner(*args, **kwargs):

        start_time = time.time()

        time.sleep(2)

        ret = func(*args, **kwargs)

        end_time = time.time()

        print("used:", end_time - start_time)

        return ret

 

return inner

 

 

@wrapper

def register(request):

    if request.method == "GET":

        return render(request, "register.html")

    if request.method == "POST":

        username = request.POST.get("username")

        password = request.POST.get("pwd")

        print(username)

        print(password)

        User.objects.create_user(username=username, password=password)  # User是以個對象

        return redirect("/index/")

 

訪問的時候大概停留兩秒再進行訪問。並在後臺打印出運行後的時間。

2.使用裝飾器裝飾CBV

類中的方法與獨立函數不徹底相同,所以不能直接將函數裝飾器應用於類中的方法 ,咱們須要先將其轉換爲方法裝飾器。Django中提供了method_decorator裝飾器用於將函數裝飾器轉換爲方法裝飾器。

使用以前須要先導入相應的包

from django.views import View

from django.utils.decorators import method_decorator

方式一:給某個方法加上裝飾器(此例給get方法加上)

class Register(View):

    @method_decorator(wrapper)

    def get(self, request):

        return render(request, "register.html")

 

    def post(self, request):

        username = request.POST.get("username")

        password = request.POST.get("pwd")

        print(username)

        print(password)

        User.objects.create_user(username=username, password=password)  

# User是以個對象

        return redirect("/index/")

 

方式二:加在dispatch方法上面,會給類下的全部方法加上此裝飾器

class Register(View):

    # 加在dispatch方法上面,會給類下的全部方法加上此裝飾器

    @method_decorator(wrapper)

def dispatch(self, request, *args, **kwargs):

#這樣的寫法兼容python2*

        obj = super(Register, self).dispatch(request, *args, **kwargs)  

# python3寫法以下(此方法不兼容python2*)

# obj = super().dispatch(request, *args, **kwargs)

        return obj

    def get(self, request):

        return render(request, "register.html")

 

    def post(self, request):

        username = request.POST.get("username")

        password = request.POST.get("pwd")

        print(username)

        print(password)

        User.objects.create_user(username=username, password=password)  

# User是以個對象

        return redirect("/index/")

 

此方式會給類下的全部方法加上此裝飾器,也就是在這個註冊過程運行了兩次的裝飾器,一次GET方法訪問網頁,一次POST方法註冊。

 

方式三:加在類上面

@method_decorator(wrapper, name="post")

@method_decorator(wrapper, name="get")  # 給哪一個方法加,就要指定name

class Register(View):

 

    def get(self, request):

        return render(request, "register.html")

 

    def post(self, request):

        username = request.POST.get("username")

        password = request.POST.get("pwd")

        print(username)

        print(password)

        User.objects.create_user(username=username, password=password)  # User是以個對象

        return redirect("/index/")

 

上面加裝飾器的方法是有固定格式的:

@method_decorator(裝飾器名, name="類中須要裝飾器的函數")

能夠從源碼中看出格式固定如截圖:

補充:

以上的例子都可以使用下面的前端模板register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery文件。務必在bootstrap.min.js 以前引入 -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
    <div class="row con">

        <form action="" method="post">
            {% csrf_token %}
            <div class="form-group col-sm-4 col-sm-offset-4">
                <h2>註冊用戶</h2>
                <label for="exampleInputEmail1">用戶名</label>
                <input type="text" class="form-control" id="exampleInputEmail1" placeholder="用戶名" name="username">
            </div>
            <div class="form-group col-sm-4 col-sm-offset-4">
                <label for="exampleInputPassword1">密碼</label>
                <input type="password" class="form-control" id="exampleInputPassword1" placeholder="密碼" name="pwd">
            </div>
            <div class="form-group col-sm-6 col-sm-offset-3">
                <button type="submit" class="btn btn-default col-sm-offset-2">確認</button>
                <button type="submit" class="btn btn-default col-sm-offset-2">返回</button>

            </div>

        </form>

    </div>
</div>
</body>
</html>
register.html
相關文章
相關標籤/搜索