Django框架基础知识14-类视图

MTV

view视图

wsgi函数

def index(request):

....

return HttpResponse()

特定的HTTP方法.get,post可以定义单独的方法

继承,多继承,代码分解成可以复用的组件

在urls.py中定义调用类视图

path('index/', views.IndexView.as_view(), name='index'),#类视图的调用,注意加括号

类视图的写法

class IndexView(View):
   def get(self,request):
       num = request.COOKIES.get('num', None)

       if num:
           num = int(num) + 1
       else:
           num = 1
       response = render(request, 'teacher/index.html', context={
           'num': num
      })
       response.set_cookie('num', str(num))
       return response

通用类视图

在student_list.html中定义如下

{% for student in object_lsit %}

   <p>{{ student }}</p>

object_list是listview默认的变量

类视图权限装饰器:

在urls.settings里面装饰

项目实践,看文档

from django.contrib.auth.decorators import login_required

在url中套上login_required.

path('newstudent/',login_required(views.StudentListView.as_view()),name='StudentLV'),

或者这样

class IndexView(View):
  @method_decorator(login_required)
  def get(self,request):
@method_decorator(login_required,name='dispatch')
class StudentListView(ListView):
  template_name = 'teacher/students_list.html'
  model = Students
  context_object_name = 'students'
  paginate_by = 3
  section = '学生列表'

  # @method_decorator(login_required)
  # def dispatch(self, request, *args, **kwargs):   #颁发装饰
  #     return super().dispatch(*args,**kwargs)
posted @ 2019-06-03 16:46  博立克  阅读(172)  评论(0编辑  收藏  举报