有关django的CBV

有关django的CBV

在学习django之初,都是一个视图函数对应一个url,当视图函数多的时候,会写不过来。使用类视图函数CBV,可以简化接口,让代码更简洁

以下是写法,直接拷贝去用

基本写法

  1. 创建app的路由连接(路由分发,可选)

    from django.conf.urls import url,include
    # 导入include
    
    urlpatterns = [
        # 指定分发的app目录名称
        url(r'^app01/',include("app01.urls")),
    ]
    
  2. 在应用下写分路由

    from django.conf.urls import url,include
    from app01 import views
    urlpatterns = [
        url(r'^login/', views.Login.as_view()),
    ]
    
  3. 书写类视图

    # views.py
    from django.shortcuts import render, HttpResponse
    from django.views import View
    # 必须导入View,as_view是View里的方法
    class Login(View):
    	# 会自动识别get方法,post方法
        def get(self,request):
            return render(request,'index.html')
    
        def post(self,request):
            return HttpResponse('OK')
    
    

添加装饰器

给类和类中的方法添加装饰器,需要特殊的姿势

  1. 在视图函数py文件中导入模块

    from django.utils.decorators import method_decorator
    
  2. 书写装饰器,以下为模板

    def outer(func):
        def inner(request, *args, **kwargs):
            print(request.method)
            rep = func(request, *args, **kwargs)
            return rep
        return inner
    
  3. 给类中的方法添加装饰器

    @method_decorator(outer)
    def get(self,request):
        return render(request,'index.html')
    
  4. 给整一个类添加装饰器

    @method_decorator(outer,name="dispatch")
    class Login(View):
    	...
    

    给类或函数添加装饰器都是固定的写法,dispatch就是django默认给我们定义的方法,在执行get或者post方法之前会执行的一个方法

原文地址:https://www.cnblogs.com/telecasterfanclub/p/13221212.html