django FBV&CBV

fbv与cbv是django处理请求方式的两种

FBV

fbv是指django在处理请求时使用视图函数的形式。

 from django.contrib import admin
    from django.urls import path,re_path
    from cmdb import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('add/',views.add),
        path('look/',views.look),
        re_path('update-(\d+)/',views.update),
        re_path('delete-(\d+)/',views.delete),
    ]

对应视图函数

from django.shortcuts import render,HttpResponse,redirect
from cmdb import models

def add(request):
    # models.Group.objects.create(caption='python')
    # models.Group.objects.create(caption='java')
    if request.method=='POST':
        uname=request.POST.get('name')
        upwd=request.POST.get('password')
        ugroup_id=request.POST.get('group_id')
        models.UserInfo.objects.create(name=uname,password=upwd,user_group_id=ugroup_id)
    return redirect('/look/')

CBV

cbv试吃django在处理请求时使用类来处理。具体代码就是下面
from django.contrib import admin
from django.urls import path,re_path
from cmdb import views

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('add/',views.XXX.as_view()),
        #****这里必须这种格式写,其中XXX对应的处理请求的类****
    ]

from django.http import HttpResponse
from django.views import View
#引用View类
  
class MyView(View):
''' 类中可以定义各种方法,定义了get方法和post方法,如果请求
方法为get时,django会自动调用get方法处理请求,post同理'''
      def get(self, request):
            return HttpResponse('getOK')
      def post(self, request):
            return HttpResponse('postOK')

你可能感兴趣的:(django)