类视图
范式
from django.views import View # 继承View
class IndexView(View):
def get(self, request):
#写法和函数视图一样
pass
在urls中调用的时候,和函数视图配置是不一样的。
# as_view() 类视图是需要运行
path('index/',views.IndexView.as_view(), name='index')
通用视图
简单应用
view中的定义
from django.views.generic import ListView class StudentListView(ListView):
# 指定使用的页面
template_name = 'teacher/student_list.html' # 获取模型数据
model = Students
html 中应用
# 此处的students_list,为view中定义的name,如果不定义则为object_list
{% for student in students_list %}
<p>{{ student }}</p> {% endfor %}
模块使用
class StudentListView(ListView):
# 指定使用的页面
template_name = 'teacher/student_list.html' # 获取模型数据
model = Students # 对html中的获取的名字进行修改
context_object_name = 'students_list' # 每页显示的数据
paginate_by = 3 # 页面名称
section = '学生列表' # 搜索字段
# search = self.request.GET.get('search','').strip() # 通过这个方法,改变传递在前面的模板对象列表。
def get_queryset(self):
search = self.request.GET.get('search','').strip()
per_page = self.request.GET.get('per_page', 5)
self.paginate_by = int(per_page) if search:
if search.isdigit():
sts = self.model.objects.filter(Q(qq=search)|Q(phone=search),is_deleted=False).order_by('-e_time')
else:
sts = self.model.objects.filter(name_contains=search,is_deleted=False).order_by('-e_time')
else:
ses = self.models.objects.filter(is_delete=False).order_by('-e_time')
return sts # 上下文管理,context内容传给html
def get_context_data(self, **kwargs):
context = super().get_context(**kwargs) # 继承父类
context['section'] = self.section
context['search'] = self.request.GET.get('search','').strip() # 获取的搜索内容
context['page'] = int(self.request.GET.get('page', 1)) # 获取的当前页码
context['per_page'] = self.paginate_by #继承的ListView自动帮我们做了分页,会根据self.paginate_by,page,per_page的参数来进行分页,和之前写的当前页的数据(sts=paginator.get_page(page))是一个意思。
context['students'] = context['page_obj']
return context
pege_obj html中的使用
{{ page_obj }} 在网页端显示的方式是一个对象:
<Page 1 of 6>
DetailView
from django.views.generic import DetailView class StudentDetailView(DetailView):
template_name = 'teacher/detail'
model = Students
# urls.py中 应用 path('detail/<int:pk>',view.StudentDetailView.as_view(),name='detail')
html 中应用
{{ object.name }}
{{ object.sex }}
{{ object.studentsdetail.college }}
类视图的权限装饰
在urls.py文件中使用
from django.contrib.auth.decorators import login_required path('student/',login_required(views.StudentListView.as_view()),name='stuent')
# 一般使用在项目根urls中
view中使用的权限类装饰
方法一:定义函数 from django.utils.decorators import method_decorator class StudentListView(ListView):
pass
当前的通用类视图没有显式指示一个get、post # 分发get,post
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(*args, **kwargs) def get_queryset(self): def get_context_data(self.**kwargs):
方法二:装饰类 @method)decorator(login_required, name='dispatch')
class StudentListView(ListView):
pass