Generic View Reference

Chapter 10 introduced generic views but left out some of the gory details. This appendix describes each generic view along with a summary of options each view can take. Be sure to read Chapter 10 before trying to understand the reference material that follows. You might want to refer back to the Book, Publisher, and Author objects defined in that chapter; the examples that follow use these models. If you want to dig deeper into more advanced generic view topics (like using mixins with the class-based views), see the Django Project website.

Common Arguments to Generic Views

Most of these views take a large number of arguments that can change the generic view’s behavior. Many of these arguments work the same across multiple views. Table C-1 describes each of these common arguments; anytime you see one of these arguments in a generic view’s argument list, it will work as described in the table.

Table C-1: Common Generic View Arguments

Argument Description
allow_empty A Boolean specifying whether to display the page if no objects are available. If this is False and no objects are available, the view will raise a 404 error instead of displaying an empty page. By default, this is True.
context_processors A list of additional template-context processors (besides the defaults) to apply to the view’s template. See Chapter 9 for information on template context processors.
extra_context A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.
mimetype The MIME type to use for the resulting document. It defaults to the value of the DEFAULT_MIME_TYPE setting, which is text/html if you haven’t changed it.
queryset A QuerySet (i.e., something like Author.objects.all()) to read objects from. See Appendix B for more information about QuerySet objects. Most generic views require this argument.
template_loader The template loader to use when loading the template. By default, it’s django.template.loader. See Chapter 9 for information on template loaders.
template_name The full name of a template to use in rendering the page. This lets you override the default template name derived from the QuerySet.
template_object_name The name of the template variable to use in the template context. By default, this is ‘object’. Views that list more than one object (i.e., object_list views and various objects-for-date views) will append ‘_list’ to the value of this parameter.

Simple Generic Views

The module django.views.generic.base contains simple views that handle a couple of common cases: rendering a template when no view logic is needed and issuing a redirect.

Rendering a Template – TemplateView

This view renders a given template, passing it a context with keyword arguments captured in the URL.

Example:

Given the following URLconf:

from django.conf.urls import url

    from myapp.views import HomePageView

    urlpatterns = [
        url(r'^$', HomePageView.as_view(), name='home'),
    ]

And a sample views.py:

from django.views.generic.base import TemplateView
from articles.models import Article

class HomePageView(TemplateView):

    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        context['latest_articles'] = Article.objects.all()[:5]
        return context a request to `/` 

would render the template home.html, returning a context containing a list of the top 5 articles.

Redirecting to Another URL

django.views.generic.base.RedirectView() redirects to a given URL.

The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any “%” characters in the URL must be written as “%%” so that Python will convert them to a single percent sign on output.

If the given URL is None, Django will return an HttpResponseGone (410).

Example views.py:

from django.shortcuts import get_object_or_404 
from django.views.generic.base import RedirectView

from articles.models import Article

class ArticleCounterRedirectView(RedirectView):

    permanent = False
    query_string = True
    pattern_name = 'article-detail'

    def get_redirect_url(self, *args, **kwargs):
        article = get_object_or_404(Article, pk=kwargs['pk'])
        article.update_counter()
        return super(ArticleCounterRedirectView, 
                     self).get_redirect_url(*args, **kwargs)

Example urls.py:

from django.conf.urls import url
from django.views.generic.base import RedirectView

from article.views import ArticleCounterRedirectView, ArticleDetail

urlpatterns = [
    url(r'^counter/(?P<pk>[0-9]+)/$', 
        ArticleCounterRedirectView.as_view(), 
        name='article-counter'),
    url(r'^details/(?P<pk>[0-9]+)/$', 
        ArticleDetail.as_view(),
        name='article-detail'),
    url(r'^go-to-django/$', 
        RedirectView.as_view(url='http://djangoproject.com'), 
        name='go-to-django'),
]
Attributes
url

The URL to redirect to, as a string. Or None to raise a 410 (Gone) HTTP error.

pattern_name

The name of the URL pattern to redirect to. Reversing will be done using the same *args
and **kwargs as are passed in for this view.

permanent

Whether the redirect should be permanent. The only difference here is the HTTP status code returned. If True, then the redirect will use status code 301. If False, then the redirect will use status code 302. By default, permanent is True.

query_string

Whether to pass along the GET query string to the new location. If True, then the query string is appended to the URL. If False, then the query string is discarded. By default, query_string is False.

Methods

get_redirect_url(*args, **kwargs) constructs the target URL for redirection.

The default implementation uses url as a starting string and performs expansion of % named parameters in that string using the named groups captured in the URL.

If url is not set, get_redirect_url() tries to reverse the pattern_name using what was captured in the URL (both named and unnamed groups are used).

If requested by query_string, it will also append the query string to the generated URL.
Subclasses may implement any behavior they wish, as long as the method returns a redirect-ready URL string.

List/Detail Generic Views

The list/detail generic views handle the common case of displaying a list of items at one view and individual detail views of those items at another.

Lists of Objects

django.views.generic.list.ListView

Use this view to display a page representing a list of objects.

Example 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 

Example myapp/urls.py:

from django.conf.urls import url

from article.views import ArticleListView

urlpatterns = [
    url(r'^$', 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>

Detail Views

django.views.generic.detail.DetailView

This view provides a detail view of a single object.

Example 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 

Example 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'),
]

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>

Date-Based Generic Views

Date-based generic views, provided in django.views.generic.dates, are views for displaying drilldown pages for date-based data.

ArchiveIndexView

A top-level index page showing the latest objects, by date. Objects with a date in the future are not included unless you set allow_future to True.

Context

In addition to the context provided by django.views.generic.list.MultipleObjectMixin (via django.views.generic.dates.BaseDateListView), the template’s context will be:

  • date_list: A DateQuerySet object containing all years that have objects available according to queryset, represented as datetime.datetime objects, in descending order.

Notes

  • Uses a default context_object_name of latest.
  • Uses a default template_name_suffix of _archive.
  • Defaults to providing date_list by year, but this can be altered to month or day using the attribute date_list_period. This also applies to all subclass views.

Example myapp/urls.py:

from django.conf.urls import url
from django.views.generic.dates import ArchiveIndexView

from myapp.models import Article

urlpatterns = [
    url(r'^archive/$',
        ArchiveIndexView.as_view(model=Article, date_field="pub_date"),
        name="article_archive"),
]

Example myapp/article_archive.html:

<ul>
    {% for article in latest %}
        <li>{{ article.pub_date }}: {{ article.title }}</li>
    {% endfor %}
</ul>

This will output all articles.

YearArchiveView

A yearly archive page showing all available months in a given year. Objects with a date in the future are not displayed unless you set allow_future to True.

Context

In addition to the context provided by django.views.generic.list.MultipleObjectMixin (via django.views.generic.dates.BaseDateListView), the template’s context will be:

  • date_list: A DateQuerySet object containing all months that have objects available according to queryset, represented as datetime.datetime objects, in ascending order.
  • year: A date object representing the given year.
  • next_year: A date object representing the first day of the next year, according to allow_empty and allow_future.
  • previous_year: A date object representing the first day of the previous year, according to allow_empty and allow_future.

Notes

  • Uses a default template_name_suffix of _archive_year.

Example myapp/views.py:

from django.views.generic.dates import YearArchiveView

from myapp.models import Article

class ArticleYearArchiveView(YearArchiveView):
    queryset = Article.objects.all()
    date_field = "pub_date"
    make_object_list = True
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url

from myapp.views import ArticleYearArchiveView

urlpatterns = [
    url(r'^(?P<year>[0-9]{4})/$',
        ArticleYearArchiveView.as_view(),
        name="article_year_archive"),
]

Example myapp/article_archive_year.html:

<ul>
    {% for date in date_list %}
        <li>{{ date|date }}</li>
    {% endfor %}
</ul>
<div>
    <h1>All Articles for {{ year|date:"Y" }}</h1>
    {% for obj in object_list %}
        <p>
            {{ obj.title }} - {{ obj.pub_date|date:"F j, Y" }}
        </p>
    {% endfor %}
</div>

MonthArchiveView

A monthly archive page showing all objects in a given month. Objects with a date in the future are not displayed unless you set allow_future to True.

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be:

  • date_list: A DateQuerySet object containing all days that have objects available in the given month, according to queryset, represented as datetime.datetime objects, in ascending order.
  • month: A date object representing the given month.
  • next_month: A date object representing the first day of the next month, according to allow_empty and allow_future.
  • previous_month: A date object representing the first day of the previous month, according to allow_empty and allow_future.

Notes

  • Uses a default template_name_suffix of _archive_month.

Example myapp/views.py:

from django.views.generic.dates import MonthArchiveView

from myapp.models import Article

class ArticleMonthArchiveView(MonthArchiveView):
    queryset = Article.objects.all()
    date_field = "pub_date"
    make_object_list = True
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url

from myapp.views import ArticleMonthArchiveView

urlpatterns = [
    # Example: /2012/aug/
    url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/$',
        ArticleMonthArchiveView.as_view(),
        name="archive_month"),
    # Example: /2012/08/
    url(r'^(?P<year>[0-9]{4})/(?P<month>[0-9]+)/$',
        ArticleMonthArchiveView.as_view(month_format='%m'),
        name="archive_month_numeric"),
]

Example myapp/article_archive_month.html:

<ul>
    {% for article in object_list %}
        <li>{{ article.pub_date|date:"F j, Y" }}: 
            {{ article.title }}
        </li>
    {% endfor %}
</ul>

<p>
    {% if previous_month %}
        Previous Month: {{ previous_month|date:"F Y" }}
    {% endif %}
    {% if next_month %}
        Next Month: {{ next_month|date:"F Y" }}
    {% endif %}
</p>

WeekArchiveView

A weekly archive page showing all objects in a given week. Objects with a date in the future are not displayed unless you set allow_future to True.

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be:

  • week: A date object representing the first day of the given week.
  • next_week: A date object representing the first day of the next week, according to allow_empty and allow_future.
  • previous_week: A date object representing the first day of the previous week, according to allow_empty and allow_future.

Notes

  • Uses a default template_name_suffix of _archive_week.

Example myapp/views.py:

from django.views.generic.dates import WeekArchiveView

from myapp.models import Article

class ArticleWeekArchiveView(WeekArchiveView):
    queryset = Article.objects.all()
    date_field = "pub_date"
    make_object_list = True
    week_format = "%W"
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url

from myapp.views import ArticleWeekArchiveView

urlpatterns = [
    # Example: /2012/week/23/
    url(r'^(?P<year>[0-9]{4})/week/(?P<week>[0-9]+)/$',
        ArticleWeekArchiveView.as_view(),
        name="archive_week"),
]

Example myapp/article_archive_week.html:

<h1>Week {{ week|date:'W' }}</h1>

<ul>
    {% for article in object_list %}
        <li>{{ article.pub_date|date:"F j, Y" }}: {{
article.title }}</li>
    {% endfor %}
</ul>

<p>
    {% if previous_week %}
        Previous Week: {{ previous_week|date:"F Y" }}
    {% endif %}
    {% if previous_week and next_week %}--{% endif %}
    {% if next_week %}
        Next week: {{ next_week|date:"F Y" }}
    {% endif %}
</p>

In this example, you are outputting the week number. The default week_format in the WeekArchiveView uses week format “%U” which is based on the United States week system where the week begins on a Sunday. The “%W” format uses the ISO week format and its week begins on a Monday. The “%W” format is the same in both the strftime() and the date.

However, the date template filter does not have an equivalent output format that supports the US based week system. The date filter “%U” outputs the number of seconds since the Unix epoch.

DayArchiveView

A day archive page showing all objects in a given day. Days in the future throw a 404 error, regardless of whether any objects exist for future days, unless you set allow_future to True.

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be:

  • day: A date object representing the given day.
  • next_day: A date object representing the next day, according to allow_empty and allow_future.
  • previous_day: A date object representing the previous day, according to allow_empty and allow_future.
  • next_month: A date object representing the first day of the next month, according to allow_empty and allow_future.
  • previous_month: A date object representing the first day of the previous month, according to allow_empty and allow_future.

Notes

  • Uses a default template_name_suffix of _archive_day.

Example myapp/views.py:

from django.views.generic.dates import DayArchiveView

from myapp.models import Article

class ArticleDayArchiveView(DayArchiveView):
    queryset = Article.objects.all()
    date_field = "pub_date"
    make_object_list = True
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url

from myapp.views import ArticleDayArchiveView

urlpatterns = [
    # Example: /2012/nov/10/
    url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/(?P<day>[0-9]+)/$',
        ArticleDayArchiveView.as_view(),
        name="archive_day"),
]

Example myapp/article_archive_day.html:

<h1>{{ day }}</h1>

<ul>
    {% for article in object_list %}
        <li>
        {{ article.pub_date|date:"F j, Y" }}: {{ article.title }}
        </li>
    {% endfor %}
</ul>

<p>
    {% if previous_day %}
        Previous Day: {{ previous_day }}
    {% endif %}
    {% if previous_day and next_day %}--{% endif %}
    {% if next_day %}
        Next Day: {{ next_day }}
    {% endif %}
</p>

TodayArchiveView

A day archive page showing all objects for today. This is exactly the same as django.views.generic.dates.DayArchiveView, except today’s date is used instead of the year/month/day arguments.

Notes

  • Uses a default template_name_suffix of _archive_today.

Example myapp/views.py:

from django.views.generic.dates import TodayArchiveView

from myapp.models import Article

class ArticleTodayArchiveView(TodayArchiveView):
    queryset = Article.objects.all()
    date_field = "pub_date"
    make_object_list = True
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url

from myapp.views import ArticleTodayArchiveView

urlpatterns = [
    url(r'^today/$',
        ArticleTodayArchiveView.as_view(),
        name="archive_today"),
]

Where is the example template for TodayArchiveView?

This view uses by default the same template as the DayArchiveView, which is in the previous example. If you need a different template, set the template_name attribute to be the name of the new template.

DateDetailView

A page representing an individual object. If the object has a date value in the future, the view will throw a 404 error by default, unless you set allow_future to True.

Context

  • Includes the single object associated with the model specified in the DateDetailView.

Notes

  • Uses a default template_name_suffix of _detail.

Example myapp/urls.py:

from django.conf.urls import url
from django.views.generic.dates import DateDetailView

urlpatterns = [
    url(r'^(?P<year>[0-9]+)/(?P<month>[-\w]+)/(?P<day>[0-9]+)/

      (?P<pk>[0-9]+)/$',
        DateDetailView.as_view(model=Article, date_field="pub_date"),
        name="archive_date_detail"),
]

Example myapp/article_detail.html:

<h1>{{ object.title }}</h1>

Form handling with class-based views

Form processing generally has 3 paths:

  • Initial GET (blank or prepopulated form)
  • POST with invalid data (typically redisplay form with errors)
  • POST with valid data (process the data and typically redirect)
    Implementing this yourself often results in a lot of repeated boilerplate code (see Using a form in a view). To help avoid this, Django provides a collection of generic class-based views for form processing.

Basic Forms

Given a simple contact form:

# forms.py

from django import forms

class ContactForm(forms.Form):
   name = forms.CharField()
   message = forms.CharField(widget=forms.Textarea)

   def send_email(self):
       # send email using the self.cleaned_data dictionary
       pass 

The view can be constructed using a FormView:

# views.py

from myapp.forms import ContactForm
from django.views.generic.edit import FormView

class ContactView(FormView):
   template_name = 'contact.html'
   form_class = ContactForm
   success_url = '/thanks/'

   def form_valid(self, form):
       # This method is called when valid form data has been POSTed.
       # It should return an HttpResponse.
       form.send_email()
       return super(ContactView, self).form_valid(form)

Notes:

  • FormView inherits TemplateResponseMixin so template_name can be used here.
  • The default implementation for form_valid() simply redirects to the success_url.

Model Forms

Generic views really shine when working with models. These generic views will automatically create a ModelForm, so long as they can work out which model class to use:

  • If the model attribute is given, that model class will be used.
  • If get_object() returns an object, the class of that object will be used.
  • If a queryset is given, the model for that queryset will be used.

Model form views provide a form_valid() implementation that saves the model automatically. You can override this if you have any special requirements; see below for examples.

You don’t even need to provide a success_url for CreateView or UpdateView – they will use get_absolute_url() on the model object if available.

If you want to use a custom ModelForm (for instance to add extra validation) simply set form_class on your view.

First we need to add get_absolute_url() to our Author class:

# models.py

from django.core.urlresolvers import reverse
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)

    def get_absolute_url(self):
        return reverse('author-detail', kwargs={'pk': self.pk})

Then we can use CreateView and friends to do the actual work. Notice how we’re just configuring the generic class-based views here; we don’t have to write any logic ourselves:

# views.py

from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

class AuthorUpdate(UpdateView):
    model = Author
    fields = ['name']

class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('author-list')

We have to use reverse_lazy() here, not just reverse as the urls are not loaded when the file is imported.

The fields attribute works the same way as the fields attribute on the inner Meta class on ModelForm. Unless you define the form class in another way, the attribute is required and the view will raise an ImproperlyConfigured exception if it’s not.

If you specify both the fields and form_class attributes, an ImproperlyConfigured exception will be raised.

Finally, we hook these new views into the URLconf:

# urls.py

from django.conf.urls import url
from myapp.views import AuthorCreate, AuthorUpdate, AuthorDelete

urlpatterns = [
    # ...
    url(r'author/add/$', AuthorCreate.as_view(), name='author_add'),
    url(r'author/(?P<pk>[0-9]+)/$', AuthorUpdate.as_view(),  
        name='author_update'),
    url(r'author/(?P<pk>[0-9]+)/delete/$', AuthorDelete.as_view(), 
        name='author_delete'),
]

In this example:

  • CreateView and UpdateView use myapp/author_form.html
  • DeleteView uses myapp/author_confirm_delete.html
    If you wish to have separate templates for CreateView and UpdateView, you can set either template_name or template_name_suffix on your view class.

Models and request.user

To track the user that created an object using a CreateView, you can use a custom ModelForm to do this. First, add the foreign key relation to the model:

# models.py

from django.contrib.auth.models import User
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)
    created_by = models.ForeignKey(User)

    # ...
In the view, ensure that you don't include `created_by` in the list of fields to edit\
, and override `form_valid()` to add the user:

# views.py

from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super(AuthorCreate, self).form_valid(form)

Note that you’ll need to decorate this view using login_required(), or alternatively handle unauthorized users in the form_valid().

AJAX example

Here is a simple example showing how you might go about implementing a form that works for AJAX requests as well as ‘normal’ form POSTs:

from django.http import JsonResponse
from django.views.generic.edit import CreateView
from myapp.models import Author

class AjaxableResponseMixin(object):
    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return JsonResponse(data)
        else:
            return response

class AuthorCreate(AjaxableResponseMixin, CreateView):
    model = Author
    fields = ['name']