基于类的视图(Class-based views)
路由书写格式
path('register/',views.RegisterView.as_view(),name='register')
通过重写post,get,等方法实现请求
类视图一般继承自基础类(View)
内建的基于类的视图的层次结构:
基本视图:view 、TemplateView、RedirectView
通⽤显示视图:DetailView、ListView
通⽤编辑视图:FormView、CreateView、 UpdateView、DeleteView
通⽤⽇期视图: ArchiveIndexView、YearArchiveView、
MonthArchiveView、 WeekArchiveView
DayArchiveView、TodayArchiveView、DateDetailView
基于类的视图mixins
简单的mixins:ContextMixin、TemplateResponseMixin
单个对象mixins:SingleObjectMixin、
SingleObjectTemplateResponseMixin
多个对象混合:MultipleObjectMixin、
MultipleObjectTemplateResponseMixin
例子
class RegisterView(View):
def get(self,request):
return render(request,"App/register.html")
def post(self,request):
# 业务处理
print("1111111")
return redirect(reverse("App:index"))
def put(self,request):
return HttpResponse("put")
def head(self,request):
return HttpResponse("head")
def delete(self,request):
return HttpResponse("delete")
其他继承
class UserListView(ListView):
# 指定查询结果集
queryset = User.objects.all()
# 指定模板文件名
template_name = 'App/list.html'
# 分页,每页10条记录
paginate_by = 10
class UserDetailView(DetailView):
template_name = 'App/detail.html'
# 参数名称是uid,并且是主键
pk_url_kwarg = 'uid'
# 模板中所用参数名称
context_object_name = 'user'
# 查询所用模型
model = User
class UserAddView(CreateView):
template_name = 'App/add.html'
# form_class = UserForm
model = User
# 提交成功后跳转的地址
success_url = reverse_lazy("App:index")
# 确定你用的是哪个表单
def get_form(self, form_class=None):
if self.request.method == "GET":
return UserForm()
else:
return UserForm(self.request.POST)
def form_valid(self, form):
print(form.cleaned_data)
# 保存数据
user = User(**form.cleaned_data)
user.save()
return redirect(reverse("App:index"))
def form_invalid(self, form):
print(form)
return super().form_invalid(form)
自定义装饰器
def wrapper(func):
def inner(*args,**kwargs):
print("*"*10)
return func(*args,**kwargs)
return inner
给类所有http的方法添加装饰器 name是被装饰的方法名(注意不是类名)
# @method_decorator(wrapper,name='dispatch')
# @method_decorator(csrf_exempt,name='dispatch')
@method_decorator(csrf_exempt,name='dispatch')
class ExampleView(View):
def get(self,request):
print("get")
return HttpResponse("get")
为特定的方法添加装饰器
# @method_decorator(装饰器函数名)
def post(self,request):
print("post")
return HttpResponse("post")