Generic display views

The two following generic class-based views are designed to display data. Onmany projects they are typically the most commonly used views.

DetailView

  • class django.views.generic.detail.DetailView
  • While this view is executing, self.object will contain the object thatthe view is operating upon.

Ancestors (MRO)

This view inherits methods and attributes from the following views:

  1. from django.utils import timezone
  2. from django.views.generic.detail import DetailView
  3.  
  4. from articles.models import Article
  5.  
  6. class ArticleDetailView(DetailView):
  7.  
  8. model = Article
  9.  
  10. def get_context_data(self, **kwargs):
  11. context = super().get_context_data(**kwargs)
  12. context['now'] = timezone.now()
  13. return context

Example myapp/urls.py:

  1. from django.urls import path
  2.  
  3. from article.views import ArticleDetailView
  4.  
  5. urlpatterns = [
  6. path('<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'),
  7. ]

Example myapp/article_detail.html:

  1. <h1>{{ object.headline }}</h1>
  2. <p>{{ object.content }}</p>
  3. <p>Reporter: {{ object.reporter }}</p>
  4. <p>Published: {{ object.pub_date|date }}</p>
  5. <p>Date: {{ now|date }}</p>

ListView

  • class django.views.generic.list.ListView
  • A page representing a list of objects.

While this view is executing, self.object_list will contain the list ofobjects (usually, but not necessarily a queryset) that the view isoperating upon.

Ancestors (MRO)

This view inherits methods and attributes from the following views:

  1. from django.utils import timezone
  2. from django.views.generic.list import ListView
  3.  
  4. from articles.models import Article
  5.  
  6. class ArticleListView(ListView):
  7.  
  8. model = Article
  9. paginate_by = 100 # if pagination is desired
  10.  
  11. def get_context_data(self, **kwargs):
  12. context = super().get_context_data(**kwargs)
  13. context['now'] = timezone.now()
  14. return context

Example myapp/urls.py:

  1. from django.urls import path
  2.  
  3. from article.views import ArticleListView
  4.  
  5. urlpatterns = [
  6. path('', ArticleListView.as_view(), name='article-list'),
  7. ]

Example myapp/article_list.html:

  1. <h1>Articles</h1>
  2. <ul>
  3. {% for article in object_list %}
  4. <li>{{ article.pub_date|date }} - {{ article.headline }}</li>
  5. {% empty %}
  6. <li>No articles yet.</li>
  7. {% endfor %}
  8. </ul>

If you're using pagination, you can adapt the example template fromthe pagination docs. Change instances ofcontacts in that example template to page_obj.

  • class django.views.generic.list.BaseListView
  • A base view for displaying a list of objects. It is not intended to be useddirectly, but rather as a parent class of thedjango.views.generic.list.ListView or other views representinglists of objects.

Ancestors (MRO)

This view inherits methods and attributes from the following views: