通用显示视图
以下两个通用的基于类的视图旨在显示数据。在许多项目中,它们通常是最常用的视图。
django.views.generic.detail.DetailView
在执行此视图时,self.object将包含视图正在操作的对象。
此视图从以下视图继承方法和属性:
django.views.generic.detail.SingleObjectTemplateResponseMixin
django.views.generic.base.TemplateResponseMixin
django.views.generic.detail.BaseDetailView
django.views.generic.detail.SingleObjectMixin
django.views.generic.base.View
示例myapp / views.py:
from django.utils import timezone
from django.views.generic.detail import DetailView
from articles.models import Article
class ArticleDetailView(DetailView):
model = Article
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context
示例myapp / urls.py:
from django.urls import path
from article.views import ArticleDetailView
urlpatterns = [
path('/', ArticleDetailView.as_view(), name='article-detail'),
]
示例myapp / article_detail.html:
{{ object.headline }}
{{ object.content }}
Reporter: {{ object.reporter }}
Published: {{ object.pub_date|date }}
Date: {{ now|date }}
django.views.generic.list.ListView
表示对象列表的页面。
在执行此视图时,self.object_list将包含视图正在操作的对象列表(通常但不一定是查询集)。
此视图从以下视图继承方法和属性:
django.views.generic.list.MultipleObjectTemplateResponseMixin
django.views.generic.base.TemplateResponseMixin
django.views.generic.list.BaseListView
django.views.generic.list.MultipleObjectMixin
django.views.generic.base.View
示例views.py:
from django.utils import timezone
from django.views.generic.list import ListView
from articles.models import Article
class ArticleListView(ListView):
model = Article
paginate_by = 100 # if pagination is desired
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context
示例myapp / urls.py:
from django.urls import path
from article.views import ArticleListView
urlpatterns = [
path('', ArticleListView.as_view(), name='article-list'),
]
示例myapp / article_list.html:
Articles
{% for article in object_list %}
- {{ article.pub_date|date }} - {{ article.headline }}
{% empty %}
- No articles yet.
{% endfor %}
如果您正在使用分页,则可以从分页文档中调整示例模板。contacts将该示例模板中的实例更改 为page_obj。
类django.views.generic.list.BaseListView
用于显示对象列表的基本视图。它不是直接使用,而是作为django.views.generic.list.ListView表示对象列表的其他视图的父类 。
此视图从以下视图继承方法和属性:
django.views.generic.list.MultipleObjectMixin
django.views.generic.base.View
方法
get(请求,* args,** kwargs)
添加object_list到上下文。如果 allow_empty 为True则显示空列表。如果 allow_empty为False,则引发404错误