通用视图类

1. class-based view 和function-based view比较

​ url ----> 函数 FBV

​ url ----> 类 CBV

​ 尝试将FBV的登录功能改写成CBV方式,体会CBV的基础流程:

def login(request):
    msg = ''
    if request.method == 'POST':
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)

        verify = Administrator.objects.filter(username=username, password=password).exists()
        if verify :
            # 登录成功
            request.session['is_login'] = True
            request.session['username'] = username
            return redirect(reverse('show_class'))
        else:
            msg = '用户名或密码错误'
    return render(request, 'studentandclass/login.html', {'msg': msg})

from django.views import View

2. 使用 class-based view

​ 最简单的使用方式:使用TemplateView 直接渲染一个模板文件:

from django.conf.urls import url
from django.views.generic import TemplateView

urlpatterns = [
    url(r'^about/$', TemplateView.as_view(template_name="about.html")),
]

3. 常用内置通用视图类

​ 基础视图:

​ View ------------------- 所有类视图的基类

​ TemplateView --------------渲染一个template

​ RedirectView ----------------重定向类视图

​ 通用显示视图:

​ DetailView ---------------展示单个object

​ ListView ------------------展示多个object

​ 通用编辑视图:

​ FormView -------------- 显示一个form表单

​ CreateView ------------ 创建一个对象

​ UpdateView ------------更新对象

​ DeleteView --------------删除对象

​ 常用mixins。

​ ContextMixin --------------- 用来设置上下文

​ TemplateResponseMixin -------------------- 渲染模板

​ SingleObjectMixin ------------------------------ 用来查找单个object

​ SingleObjectTemplateResponseMixin ------------------- 将单个object渲染到模板中

​ MultipleObjectMixin -------------------------------- 用来查找多个object

​ MultipleObjectTemplateResponseMixin --------------------- 将多个object渲染到模板中

4. 在通用视图类中使用form表单

在最基础View中使用form表单:

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import View

from .forms import MyForm

class MyFormView(View):
    form_class = MyForm
    initial = {'key': 'value'}
    template_name = 'form_template.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class(initial=self.initial)
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            # 
            return HttpResponseRedirect('/success/')

        return render(request, self.template_name, {'form': form})

使用FormView:

要点:

​ template_name 指定需要将form表单渲染到哪个页面

​ form_class 指定该视图使用哪个form表单

​ success_url 指定form校验成功之后要跳转的路径

forms.py
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()
    message = forms.CharField(widget=forms.Textarea)

    def send_email(self):
        # send email using the self.cleaned_data dictionary
        pass
        
views.py
from myapp.forms import ContactForm
from django.views.generic.edit import FormView

class ContactView(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.send_email()
        return super(ContactView, self).form_valid(form)

在类视图中使用modelform只需要指定fields或者form_class即可,Django会为我们自动生成modelform。

如modelform中有些数据需要额外添加,可在通用编辑视图类中重写form_valid方法,比如:

from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super(AuthorCreate, self).form_valid(form)



你可能感兴趣的:(Django)