以下两个基于类的通用视图旨在显示数据。在许多项目中,它们通常是最常用的视图。
DetailView
¶django.views.generic.detail.
DetailView
¶当该视图执行时,self.object
将包含该视图正在操作的对象。
祖先(MRO)
该视图从以下视图继承方法和属性。
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
方法流程图
setup()
dispatch()
http_method_not_allowed()
get_template_names()
get_slug_field()
get_queryset()
get_object()
get_context_object_name()
get_context_data()
get()
render_to_response()
示例 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("<slug:slug>/", ArticleDetailView.as_view(), name="article-detail"),
]
示例 myapp/article_detail.html:
<h1>{{ object.headline }}</h1>
<p>{{ object.content }}</p>
<p>Reporter: {{ object.reporter }}</p>
<p>Published: {{ object.pub_date|date }}</p>
<p>Date: {{ now|date }}</p>
ListView
¶django.views.generic.list.
ListView
¶一个表示对象列表的页面。
当该视图执行时,self.object_list
将包含该视图正在操作的对象列表(通常,但不一定是查询集)。
祖先(MRO)
该视图从以下视图继承方法和属性。
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
方法流程图
setup()
dispatch()
http_method_not_allowed()
get_template_names()
get_queryset()
get_context_object_name()
get_context_data()
get()
render_to_response()
示例 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:
<h1>Articles</h1>
<ul>
{% for article in object_list %}
<li>{{ article.pub_date|date }} - {{ article.headline }}</li>
{% empty %}
<li>No articles yet.</li>
{% endfor %}
</ul>
If you're using pagination, you can adapt the example template from the pagination docs.
django.views.generic.list.
BaseListView
¶一个用于显示对象列表的基础视图。它不打算直接使用,而是作为 django.view.generic.list.ListView
或其他代表对象列表的视图的父类。
祖先(MRO)
该视图从以下视图继承方法和属性。
方法
get
(request, *args, **kwargs)¶添加 object_list
到上下文。如果 allow_empty
为 True,则显示一个空列表。如果 allow_empty
为 False,则引发一个 404 错误。
5月 31, 2023