Django-FBV 和 CBV

FBV 和 CBV

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

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

看代碼:

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(request):
    if request.method=="POST":
        print('method is :' + request.method)
    elif request.method=="GET":
        print('method is :' + request.method)

    return render(request, "index.html")

注意此處定義的是函數(shù)def index(request):

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(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, request):
       print(‘method is :‘ + request.method)
       return render(request, ‘index.html‘)

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

注:這里是類不在是函數(shù)了; 類要繼承 View ,類中函數(shù)名必須小寫。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容