第五章——CBV视图
数据显示视图
RedirectView 重定向视图
class TurnTO(RedirectView):
permanent = False
url = 'http://192.168.241.128:8080/download/file1'
query_string = True
def get_redirect_url(self, *args, **kwargs):
print('i am here')
return super().get_redirect_url(*args, **kwargs)
def get(self, request, *args, **kwargs):
print('hello world.')
return super().get(request, *args, **kwargs)
基础视图 TemplateView
from django.views.generic.base import TemplateView
class Index(TemplateView):
template_name = 'index1.html'
template_engine = None
content_type = None
extra_context = {'title': 'this is get'}
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['value'] = 'Django'
return context
def post(self, request, *args, **kwargs):
self.extra_context = {'title': 'this is post'}
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
列表视图 ListView
from django.views.generic import ListView
from .models import PersonInfo
class PersonInfoView(ListView):
template_name = 'personinfo.html'
extra_context = {'title': "人员信息表"}
queryset = PersonInfo.objects.all()
paginate_by = 1
context_object_name = 'personinfo'
详细视图 DetailView
from django.views.generic import DetailView
class PersonInfoDetailView(DetailView):
template_name = 'info.html'
extra_context = {'title': "人员信息表"}
slug_field = 'age'
slug_url_kwarg = 'age'
pk_url_kwarg = 'pk'
model = PersonInfo
context_object_name = 'personinfo'
query_pk_and_slug = False
数据操作视图
from django.views.generic.edit import FormView
from .form import PersonInfoForm
def result(request):
return HttpResponse('success')
class ShowForm(FormView):
initial = {'name': 'cooper', 'age': 20}
template_name = 'show.html'
success_url = '/result'
form_class = PersonInfoForm
extra_context = {'title': '人员信息表'}
from django.views.generic.edit import CreateView
class CreateForm(CreateView):
initial = {'name': 'cooper', 'age': 21}
template_name = 'show.html'
success_url = '/result'
model = PersonInfo
fields = ['name', 'age']
extra_context = {"title": "人员信息表"}
from django.views.generic.edit import UpdateView
class UpdateForm(UpdateView):
template_name = 'show.html'
success_url = '/result'
model = PersonInfo
fields = ['name', 'age']
slug_url_kwarg = 'age'
slug_field = 'age'
context_object_name = 'personinfo'
extra_context = {'title': '人员信息表'}
from django.views.generic.edit import DeleteView
class DeleteForm(DeleteView):
template_name = 'show.html'
success_url = '/result'
model = PersonInfo
context_object_name = 'personinfo'
extra_context = {'title': '人员信息表'}
pk_url_kwarg = 'pk'
日期筛选视图
from .models import TimeInfo
from django.views.generic.dates import MonthArchiveView
class MonthView(MonthArchiveView):
allow_empty = True
allow_future = True
context_object_name = 'mylist'
template_name = 'time.html'
model = TimeInfo
date_field = 'hiredate'
queryset = TimeInfo.objects.all()
year_format = '%Y'
month_format = '%m'
paginate_by = 50