Django 9 常用通用视图分析
Django 通用视图是一种快速创建Web应用程序视图的方法。以下是Django 9 常用的几个通用类视图及其功能简述:
ListView
:列表视图用于显示查询集(QuerySet)的列表。
from django.views.generic import ListView
from myapp.models import MyModel
class MyModelListView(ListView):
model = MyModel
template_name = 'myapp/mymodel_list.html'
context_object_name = 'mymodel_list'
paginate_by = 25
DetailView
:详情视图用于显示单个数据库对象的详细信息。
from django.views.generic import DetailView
from myapp.models import MyModel
class MyModelDetailView(DetailView):
model = MyModel
template_name = 'myapp/mymodel_detail.html'
CreateView
:创建视图用于创建新的数据库对象。
from django.views.generic import CreateView
from myapp.models import MyModel
from myapp.forms import MyModelForm
class MyModelCreateView(CreateView):
model = MyModel
form_class = MyModelForm
template_name = 'myapp/mymodel_form.html'
UpdateView
:更新视图用于更新现有的数据库对象。
from django.views.generic import UpdateView
from myapp.models import MyModel
from myapp.forms import MyModelForm
class MyModelUpdateView(UpdateView):
model = MyModel
form_class = MyModelForm
template_name = 'myapp/mymodel_form.html'
DeleteView
:删除视图用于删除现有的数据库对象。
from django.views.generic import DeleteView
from myapp.models import MyModel
class MyModelDeleteView(DeleteView):
model = MyModel
template_name = 'myapp/confirm_delete.html'
success_url = '/myapp/'
ArchiveIndexView
:归档索引视图用于显示特定日期的对象列表。
from django.views.generic import ArchiveIndexView
from myapp.models import MyModel
class MyModelArchiveIndexView(ArchiveIndexView):
model = MyModel
date_field = 'timestamp'
template_name = 'myapp/mymodel_archive.html'
YearArchiveView
:年度归档视图用于显示特定年份的对象列表。
from django.views.generic import YearArchiveView
from myapp.models import MyModel
class MyModelYearArchiveView(YearArchiveView):
model = MyModel
template_name = 'myapp/mymodel_year_archive.html'
make_object_list = True
MonthArchiveView
:月度归档视图用于显示特定月份的对象列表。
from django.views.generic import MonthArchiveView
from myapp.models import MyModel
class MyModelMonthArchiveView(MonthArchiveView):
model = MyModel
template_name = 'myapp/
评论已关闭