Skip to main content

通用显示视图

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

DetailView

class django.views.generic.detail.DetailView

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

祖先(MRO)

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

方法流程图

  1. dispatch()

  2. http_method_not_allowed()

  3. get_template_names()

  4. get_slug_field()

  5. get_queryset()

  6. get_object()

  7. get_context_object_name()

  8. get_context_data()

  9. get()

  10. render_to_response()

示例myapp/views.py:

from django.views.generic.detail import DetailView
from django.utils import timezone

from articles.models import Article

class ArticleDetailView(DetailView):

    model = Article

    def get_context_data(self, **kwargs):
        context = super(ArticleDetailView, self).get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

示例myapp/urls.py:

from django.conf.urls import url

from article.views import ArticleDetailView

urlpatterns = [
    url(r'^(?P<slug>[-\w]+)/$', 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

class django.views.generic.list.ListView

表示对象列表的页面。

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

祖先(MRO)

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

方法流程图

  1. dispatch()

  2. http_method_not_allowed()

  3. get_template_names()

  4. get_queryset()

  5. get_context_object_name()

  6. get_context_data()

  7. get()

  8. render_to_response()

示例views.py:

from django.views.generic.list import ListView
from django.utils import timezone

from articles.models import Article

class ArticleListView(ListView):

    model = Article

    def get_context_data(self, **kwargs):
        context = super(ArticleListView, self).get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

示例myapp/urls.py:

from django.conf.urls import url

from article.views import ArticleListView

urlpatterns = [
    url(r'^$', 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>
class django.views.generic.list.BaseListView

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

祖先(MRO)

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

方法

get(request, *args, **kwargs)

object_list 添加到上下文。如果 allow_empty 为True,则显示一个空列表。如果 allow_empty 为False,则引发404错误。