django中的FBV和CBV


                  django中請求處理方式有2種:FBV 和 CBV

 

一、FBV

FBV(function base views) 就是在視圖里使用函數處理請求。

看代碼:

urls.py

from django.conf.urls import url, include
# from django.contrib import admin
from mytest import views

urlpatterns = [
    # url(r‘^admin/‘, admin.site.urls),
    url(r‘^index/‘, views.index),
]

views.py

from django.shortcuts import render


def index(req):
    if req.method == ‘POST‘:
        print(‘method is :‘ + req.method)
    elif req.method == ‘GET‘:
        print(‘method is :‘ + req.method)
    return render(req, ‘index.html‘)

注意此處定義的是函數【def index(req):】

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <form action="" method="post">
        <input type="text" name="A" />
        <input type="submit" name="b" value="提交" />
    </form>
</body>
</html>

上面就是FBV的使用。

二、CBV

CBV(class base views) 就是在視圖里使用類處理請求。

將上述代碼中的urls.py 修改為如下:

from mytest import views

urlpatterns = [
    # url(r‘^index/‘, views.index),
    url(r‘^index/‘, views.Index.as_view()),
]

注:url(r‘^index/‘, views.Index.as_view()),  是固定用法。

將上述代碼中的views.py 修改為如下:

from django.views import View


class Index(View):
    def get(self, req):
        print(‘method is :‘ + req.method)
        return render(req, ‘index.html‘)

    def post(self, req):
        print(‘method is :‘ + req.method)
        return render(req, ‘index.html‘)

注:類要繼承 View ,類中函數名必須小寫。

 

兩種方式沒有優劣,都可以使用。

django中的FBV和CBV

標簽:base   text   onf   div   spa   2種   inpu   site   .py   

原文:http://www.cnblogs.com/wumingxiaoyao/p/6513981.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM