通用显示视图

下面两个基于类的通用视图设计用于显示数据。在许多项目中,它们通常是最常用的视图。

DetailView

class django.views.generic.detail.DetailView

在执行此视图时, self.object 将包含视图正在操作的对象。

Ancestors (MRO)

此视图从以下视图继承方法和属性:

方法流程图

  1. setup()

  2. dispatch()

  3. http_method_not_allowed()

  4. get_template_names()

  5. get_slug_field()

  6. get_queryset()

  7. get_object()

  8. get_context_object_name()

  9. get_context_data()

  10. get()

  11. render_to_response()

Example 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

Example myapp/urls.py ::

from django.urls import path

from article.views import ArticleDetailView

urlpatterns = [
    path("<slug:slug>/", ArticleDetailView.as_view(), name="article-detail"),
]

Example 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>
class django.views.generic.detail.BaseDetailView

用于显示单个对象的基本视图。它不打算直接使用,而是用作 django.views.generic.detail.DetailView 或表示单个对象的细节的其他视图。

Ancestors (MRO)

此视图从以下视图继承方法和属性:

Methods

get(request, *args, **kwargs)

添加 object 到上下文中去。

ListView

class django.views.generic.list.ListView

表示对象列表的页。

在执行此视图时, self.object_list 将包含视图正在操作的对象列表(通常,但不一定是查询集)。

Ancestors (MRO)

此视图从以下视图继承方法和属性:

方法流程图

  1. setup()

  2. dispatch()

  3. http_method_not_allowed()

  4. get_template_names()

  5. get_queryset()

  6. get_context_object_name()

  7. get_context_data()

  8. get()

  9. render_to_response()

示例视图.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

Example myapp/urls.py ::

from django.urls import path

from article.views import ArticleListView

urlpatterns = [
    path("", ArticleListView.as_view(), name="article-list"),
]

Example 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>

如果您正在使用分页,则可以调整 example template from the pagination docs

class django.views.generic.list.BaseListView

用于显示对象列表的基础视图。它不打算直接使用,而是作为 django.views.generic.list.ListView 或其他表示对象列表的视图。

Ancestors (MRO)

此视图从以下视图继承方法和属性:

Methods

get(request, *args, **kwargs)

添加 object_list 根据上下文。如果 allow_empty 为true,则显示空列表。如果 allow_empty 如果为假,则引发404错误。