Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixed #6735 -- Added class-based views.

This patch is the result of the work of many people, over many years.
To try and thank individuals would inevitably lead to many people
being left out or forgotten -- so rather than try to give a list that
will inevitably be incomplete, I'd like to thank *everybody* who
contributed in any way, big or small, with coding, testing, feedback
and/or documentation over the multi-year process of getting this into
trunk.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@14254 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 0fcb09455729113f64a9873ca40bffd009b9bc5f 1 parent fa2159f
Russell Keith-Magee freakboy3742 authored
Showing with 5,029 additions and 83 deletions.
  1. +9 −0 django/views/generic/__init__.py
  2. +190 −0 django/views/generic/base.py
  3. +7 −1 django/views/generic/create_update.py
  4. +7 −0 django/views/generic/date_based.py
  5. +595 −0 django/views/generic/dates.py
  6. +142 −0 django/views/generic/detail.py
  7. +249 −0 django/views/generic/edit.py
  8. +138 −0 django/views/generic/list.py
  9. +7 −0 django/views/generic/list_detail.py
  10. +6 −0 django/views/generic/simple.py
  11. +4 −2 docs/index.txt
  12. +9 −0 docs/internals/deprecation.txt
  13. +81 −77 docs/intro/tutorial04.txt
  14. +1,391 −0 docs/ref/class-based-views.txt
  15. +1 −1  docs/ref/generic-views.txt
  16. +9 −1 docs/ref/index.txt
  17. +29 −0 docs/releases/1.3.txt
  18. +535 −0 docs/topics/class-based-views.txt
  19. +127 −0 docs/topics/generic-views-migration.txt
  20. +9 −1 docs/topics/index.txt
  21. 0  tests/regressiontests/generic_views/__init__.py
  22. +233 −0 tests/regressiontests/generic_views/base.py
  23. +352 −0 tests/regressiontests/generic_views/dates.py
  24. +71 −0 tests/regressiontests/generic_views/detail.py
  25. +233 −0 tests/regressiontests/generic_views/edit.py
  26. +47 −0 tests/regressiontests/generic_views/fixtures/generic-views-test-data.json
  27. +11 −0 tests/regressiontests/generic_views/forms.py
  28. +129 −0 tests/regressiontests/generic_views/list.py
  29. +41 −0 tests/regressiontests/generic_views/models.py
  30. +1 −0  tests/regressiontests/generic_views/templates/generic_views/about.html
  31. +1 −0  tests/regressiontests/generic_views/templates/generic_views/apple_detail.html
  32. +1 −0  tests/regressiontests/generic_views/templates/generic_views/artist_detail.html
  33. +1 −0  tests/regressiontests/generic_views/templates/generic_views/artist_form.html
  34. +1 −0  tests/regressiontests/generic_views/templates/generic_views/author_confirm_delete.html
  35. +1 −0  tests/regressiontests/generic_views/templates/generic_views/author_detail.html
  36. +1 −0  tests/regressiontests/generic_views/templates/generic_views/author_form.html
  37. +3 −0  tests/regressiontests/generic_views/templates/generic_views/author_list.html
  38. +3 −0  tests/regressiontests/generic_views/templates/generic_views/author_objects.html
  39. +1 −0  tests/regressiontests/generic_views/templates/generic_views/author_view.html
  40. +1 −0  tests/regressiontests/generic_views/templates/generic_views/book_archive.html
  41. +1 −0  tests/regressiontests/generic_views/templates/generic_views/book_archive_day.html
  42. +1 −0  tests/regressiontests/generic_views/templates/generic_views/book_archive_month.html
  43. +1 −0  tests/regressiontests/generic_views/templates/generic_views/book_archive_week.html
  44. +1 −0  tests/regressiontests/generic_views/templates/generic_views/book_archive_year.html
  45. +1 −0  tests/regressiontests/generic_views/templates/generic_views/book_detail.html
  46. +3 −0  tests/regressiontests/generic_views/templates/generic_views/book_list.html
  47. +1 −0  tests/regressiontests/generic_views/templates/generic_views/confirm_delete.html
  48. +1 −0  tests/regressiontests/generic_views/templates/generic_views/detail.html
  49. +1 −0  tests/regressiontests/generic_views/templates/generic_views/form.html
  50. +3 −0  tests/regressiontests/generic_views/templates/generic_views/list.html
  51. +1 −0  tests/regressiontests/generic_views/templates/generic_views/page_template.html
  52. +1 −0  tests/regressiontests/generic_views/templates/registration/login.html
  53. +5 −0 tests/regressiontests/generic_views/tests.py
  54. +186 −0 tests/regressiontests/generic_views/urls.py
  55. +145 −0 tests/regressiontests/generic_views/views.py
9 django/views/generic/__init__.py
View
@@ -1,3 +1,12 @@
+from django.views.generic.base import View, TemplateView, RedirectView
+from django.views.generic.dates import (ArchiveIndexView, YearArchiveView, MonthArchiveView,
+ WeekArchiveView, DayArchiveView, TodayArchiveView,
+ DateDetailView)
+from django.views.generic.detail import DetailView
+from django.views.generic.edit import CreateView, UpdateView, DeleteView
+from django.views.generic.list import ListView
+
+
class GenericViewError(Exception):
"""A problem in a generic view."""
pass
190 django/views/generic/base.py
View
@@ -0,0 +1,190 @@
+import copy
+from django import http
+from django.core.exceptions import ImproperlyConfigured
+from django.template import RequestContext, loader
+from django.utils.translation import ugettext_lazy as _
+from django.utils.functional import update_wrapper
+from django.utils.log import getLogger
+
+logger = getLogger('django.request')
+
+class classonlymethod(classmethod):
+ def __get__(self, instance, owner):
+ if instance is not None:
+ raise AttributeError("This method is available only on the view class.")
+ return super(classonlymethod, self).__get__(instance, owner)
+
+class View(object):
+ """
+ Intentionally simple parent class for all views. Only implements
+ dispatch-by-method and simple sanity checking.
+ """
+
+ http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
+
+ def __init__(self, **kwargs):
+ """
+ Constructor. Called in the URLconf; can contain helpful extra
+ keyword arguments, and other things.
+ """
+ # Go through keyword arguments, and either save their values to our
+ # instance, or raise an error.
+ for key, value in kwargs.iteritems():
+ setattr(self, key, value)
+
+ @classonlymethod
+ def as_view(cls, **initkwargs):
+ """
+ Main entry point for a request-response process.
+ """
+ # sanitize keyword arguments
+ for key in initkwargs:
+ if key in cls.http_method_names:
+ raise TypeError(u"You tried to pass in the %s method name as a "
+ u"keyword argument to %s(). Don't do that."
+ % (key, cls.__name__))
+ if not hasattr(cls, key):
+ raise TypeError(u"%s() received an invalid keyword %r" % (
+ cls.__name__, key))
+
+ def view(request, *args, **kwargs):
+ self = cls(**initkwargs)
+ return self.dispatch(request, *args, **kwargs)
+
+ # take name and docstring from class
+ update_wrapper(view, cls, updated=())
+
+ # and possible attributes set by decorators
+ # like csrf_exempt from dispatch
+ update_wrapper(view, cls.dispatch, assigned=())
+ return view
+
+ def dispatch(self, request, *args, **kwargs):
+ # Try to dispatch to the right method for that; if it doesn't exist,
+ # defer to the error handler. Also defer to the error handler if the
+ # request method isn't on the approved list.
+ if request.method.lower() in self.http_method_names:
+ handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
+ else:
+ handler = self.http_method_not_allowed
+ self.request = request
+ self.args = args
+ self.kwargs = kwargs
+ return handler(request, *args, **kwargs)
+
+ def http_method_not_allowed(self, request, *args, **kwargs):
+ allowed_methods = [m for m in self.http_method_names if hasattr(self, m)]
+ return http.HttpResponseNotAllowed(allowed_methods)
+
+
+class TemplateResponseMixin(object):
+ """
+ A mixin that can be used to render a template.
+ """
+ template_name = None
+
+ def render_to_response(self, context):
+ """
+ Returns a response with a template rendered with the given context.
+ """
+ return self.get_response(self.render_template(context))
+
+ def get_response(self, content, **httpresponse_kwargs):
+ """
+ Construct an `HttpResponse` object.
+ """
+ return http.HttpResponse(content, **httpresponse_kwargs)
+
+ def render_template(self, context):
+ """
+ Render the template with a given context.
+ """
+ context_instance = self.get_context_instance(context)
+ return self.get_template().render(context_instance)
+
+ def get_context_instance(self, context):
+ """
+ Get the template context instance. Must return a Context (or subclass)
+ instance.
+ """
+ return RequestContext(self.request, context)
+
+ def get_template(self):
+ """
+ Get a ``Template`` object for the given request.
+ """
+ names = self.get_template_names()
+ if not names:
+ raise ImproperlyConfigured(u"'%s' must provide template_name."
+ % self.__class__.__name__)
+ return self.load_template(names)
+
+ def get_template_names(self):
+ """
+ Return a list of template names to be used for the request. Must return
+ a list. May not be called if get_template is overridden.
+ """
+ if self.template_name is None:
+ return []
+ else:
+ return [self.template_name]
+
+ def load_template(self, names):
+ """
+ Load a list of templates using the default template loader.
+ """
+ return loader.select_template(names)
+
+
+class TemplateView(TemplateResponseMixin, View):
+ """
+ A view that renders a template.
+ """
+ def get_context_data(self, **kwargs):
+ return {
+ 'params': kwargs
+ }
+
+ def get(self, request, *args, **kwargs):
+ context = self.get_context_data(**kwargs)
+ return self.render_to_response(context)
+
+
+class RedirectView(View):
+ """
+ A view that provides a redirect on any GET request.
+ """
+ permanent = True
+ url = None
+ query_string = False
+
+ def get_redirect_url(self, **kwargs):
+ """
+ Return the URL redirect to. Keyword arguments from the
+ URL pattern match generating the redirect request
+ are provided as kwargs to this method.
+ """
+ if self.url:
+ args = self.request.META["QUERY_STRING"]
+ if args and self.query_string:
+ url = "%s?%s" % (self.url, args)
+ else:
+ url = self.url
+ return url % kwargs
+ else:
+ return None
+
+ def get(self, request, *args, **kwargs):
+ url = self.get_redirect_url(**kwargs)
+ if url:
+ if self.permanent:
+ return http.HttpResponsePermanentRedirect(url)
+ else:
+ return http.HttpResponseRedirect(url)
+ else:
+ logger.warning('Gone: %s' % self.request.path,
+ extra={
+ 'status_code': 410,
+ 'request': self.request
+ })
+ return http.HttpResponseGone()
8 django/views/generic/create_update.py
View
@@ -8,6 +8,12 @@
from django.views.generic import GenericViewError
from django.contrib import messages
+import warnings
+warnings.warn(
+ 'Function-based generic views have been deprecated; use class-based views instead.',
+ PendingDeprecationWarning
+)
+
def apply_extra_context(extra_context, context):
"""
@@ -111,7 +117,7 @@ def create_object(request, model=None, template_name=None,
form = form_class(request.POST, request.FILES)
if form.is_valid():
new_object = form.save()
-
+
msg = ugettext("The %(verbose_name)s was created successfully.") %\
{"verbose_name": model._meta.verbose_name}
messages.success(request, msg, fail_silently=True)
7 django/views/generic/date_based.py
View
@@ -7,6 +7,13 @@
from django.db.models.fields import DateTimeField
from django.http import Http404, HttpResponse
+import warnings
+warnings.warn(
+ 'Function-based generic views have been deprecated; use class-based views instead.',
+ PendingDeprecationWarning
+)
+
+
def archive_index(request, queryset, date_field, num_latest=15,
template_name=None, template_loader=loader,
extra_context=None, allow_empty=True, context_processors=None,
595 django/views/generic/dates.py
View
@@ -0,0 +1,595 @@
+import time
+import datetime
+from django.db import models
+from django.core.exceptions import ImproperlyConfigured
+from django.http import Http404
+from django.views.generic.base import View
+from django.views.generic.detail import BaseDetailView, SingleObjectTemplateResponseMixin
+from django.views.generic.list import MultipleObjectMixin, MultipleObjectTemplateResponseMixin
+
+
+class YearMixin(object):
+ year_format = '%Y'
+ year = None
+
+ def get_year_format(self):
+ """
+ Get a year format string in strptime syntax to be used to parse the
+ year from url variables.
+ """
+ return self.year_format
+
+ def get_year(self):
+ "Return the year for which this view should display data"
+ year = self.year
+ if year is None:
+ try:
+ year = self.kwargs['year']
+ except KeyError:
+ try:
+ year = self.request.GET['year']
+ except KeyError:
+ raise Http404("No year specified")
+ return year
+
+
+class MonthMixin(object):
+ month_format = '%b'
+ month = None
+
+ def get_month_format(self):
+ """
+ Get a month format string in strptime syntax to be used to parse the
+ month from url variables.
+ """
+ return self.month_format
+
+ def get_month(self):
+ "Return the month for which this view should display data"
+ month = self.month
+ if month is None:
+ try:
+ month = self.kwargs['month']
+ except KeyError:
+ try:
+ month = self.request.GET['month']
+ except KeyError:
+ raise Http404("No month specified")
+ return month
+
+ def get_next_month(self, date):
+ """
+ Get the next valid month.
+ """
+ first_day, last_day = _month_bounds(date)
+ next = (last_day + datetime.timedelta(days=1)).replace(day=1)
+ return _get_next_prev_month(self, next, is_previous=False, use_first_day=True)
+
+ def get_previous_month(self, date):
+ """
+ Get the previous valid month.
+ """
+ first_day, last_day = _month_bounds(date)
+ prev = (first_day - datetime.timedelta(days=1)).replace(day=1)
+ return _get_next_prev_month(self, prev, is_previous=True, use_first_day=True)
+
+
+class DayMixin(object):
+ day_format = '%d'
+ day = None
+
+ def get_day_format(self):
+ """
+ Get a month format string in strptime syntax to be used to parse the
+ month from url variables.
+ """
+ return self.day_format
+
+ def get_day(self):
+ "Return the day for which this view should display data"
+ day = self.day
+ if day is None:
+ try:
+ day = self.kwargs['day']
+ except KeyError:
+ try:
+ day = self.request.GET['day']
+ except KeyError:
+ raise Http404("No day specified")
+ return day
+
+ def get_next_day(self, date):
+ """
+ Get the next valid day.
+ """
+ next = date + datetime.timedelta(days=1)
+ return _get_next_prev_month(self, next, is_previous=False, use_first_day=False)
+
+ def get_previous_day(self, date):
+ """
+ Get the previous valid day.
+ """
+ prev = date - datetime.timedelta(days=1)
+ return _get_next_prev_month(self, prev, is_previous=True, use_first_day=False)
+
+
+class WeekMixin(object):
+ week_format = '%U'
+ week = None
+
+ def get_week_format(self):
+ """
+ Get a week format string in strptime syntax to be used to parse the
+ week from url variables.
+ """
+ return self.week_format
+
+ def get_week(self):
+ "Return the week for which this view should display data"
+ week = self.week
+ if week is None:
+ try:
+ week = self.kwargs['week']
+ except KeyError:
+ try:
+ week = self.request.GET['week']
+ except KeyError:
+ raise Http404("No week specified")
+ return week
+
+
+class DateMixin(object):
+ """
+ Mixin class for views manipulating date-based data.
+ """
+ date_field = None
+ allow_future = False
+
+ def get_date_field(self):
+ """
+ Get the name of the date field to be used to filter by.
+ """
+ if self.date_field is None:
+ raise ImproperlyConfigured(u"%s.date_field is required." % self.__class__.__name__)
+ return self.date_field
+
+ def get_allow_future(self):
+ """
+ Returns `True` if the view should be allowed to display objects from
+ the future.
+ """
+ return self.allow_future
+
+
+class BaseDateListView(MultipleObjectMixin, DateMixin, View):
+ """
+ Abstract base class for date-based views display a list of objects.
+ """
+ allow_empty = False
+
+ def get(self, request, *args, **kwargs):
+ self.date_list, self.object_list, extra_context = self.get_dated_items()
+ context = self.get_context_data(object_list=self.object_list,
+ date_list=self.date_list)
+ context.update(extra_context)
+ return self.render_to_response(context)
+
+ def get_dated_items(self):
+ """
+ Obtain the list of dates and itesm
+ """
+ raise NotImplemented('A DateView must provide an implementaiton of get_dated_items()')
+
+ def get_dated_queryset(self, **lookup):
+ """
+ Get a queryset properly filtered according to `allow_future` and any
+ extra lookup kwargs.
+ """
+ qs = self.get_queryset().filter(**lookup)
+ date_field = self.get_date_field()
+ allow_future = self.get_allow_future()
+ allow_empty = self.get_allow_empty()
+
+ if not allow_future:
+ qs = qs.filter(**{'%s__lte' % date_field: datetime.datetime.now()})
+
+ if not allow_empty and not qs:
+ raise Http404(u"No %s available" % unicode(qs.model._meta.verbose_name_plural))
+
+ return qs
+
+ def get_date_list(self, queryset, date_type):
+ """
+ Get a date list by calling `queryset.dates()`, checking along the way
+ for empty lists that aren't allowed.
+ """
+ date_field = self.get_date_field()
+ allow_empty = self.get_allow_empty()
+
+ date_list = queryset.dates(date_field, date_type)[::-1]
+ if date_list is not None and not date_list and not allow_empty:
+ raise Http404(u"No %s available" % unicode(qs.model._meta.verbose_name_plural))
+
+ return date_list
+
+
+
+ def get_context_data(self, **kwargs):
+ """
+ Get the context. Must return a Context (or subclass) instance.
+ """
+ items = kwargs.pop('object_list')
+ context = super(BaseDateListView, self).get_context_data(object_list=items)
+ context.update(kwargs)
+ return context
+
+
+class BaseArchiveIndexView(BaseDateListView):
+ """
+ Base class for archives of date-based items.
+
+ Requires a response mixin.
+ """
+ context_object_name = 'latest'
+
+ def get_dated_items(self):
+ """
+ Return (date_list, items, extra_context) for this request.
+ """
+ qs = self.get_dated_queryset()
+ date_list = self.get_date_list(qs, 'year')
+
+ if date_list:
+ object_list = qs.order_by('-'+self.get_date_field())
+ else:
+ object_list = qs.none()
+
+ return (date_list, object_list, {})
+
+
+class ArchiveIndexView(MultipleObjectTemplateResponseMixin, BaseArchiveIndexView):
+ """
+ Top-level archive of date-based items.
+ """
+ template_name_suffix = '_archive'
+
+
+class BaseYearArchiveView(YearMixin, BaseDateListView):
+ """
+ List of objects published in a given year.
+ """
+ make_object_list = False
+
+ def get_dated_items(self):
+ """
+ Return (date_list, items, extra_context) for this request.
+ """
+ # Yes, no error checking: the URLpattern ought to validate this; it's
+ # an error if it doesn't.
+ year = self.get_year()
+ date_field = self.get_date_field()
+ qs = self.get_dated_queryset(**{date_field+'__year': year})
+ date_list = self.get_date_list(qs, 'month')
+
+ if self.get_make_object_list():
+ object_list = qs.order_by('-'+date_field)
+ else:
+ # We need this to be a queryset since parent classes introspect it
+ # to find information about the model.
+ object_list = qs.none()
+
+ return (date_list, object_list, {'year': year})
+
+ def get_make_object_list(self):
+ """
+ Return `True` if this view should contain the full list of objects in
+ the given year.
+ """
+ return self.make_object_list
+
+
+class YearArchiveView(MultipleObjectTemplateResponseMixin, BaseYearArchiveView):
+ """
+ List of objects published in a given year.
+ """
+ template_name_suffix = '_archive_year'
+
+
+class BaseMonthArchiveView(YearMixin, MonthMixin, BaseDateListView):
+ """
+ List of objects published in a given year.
+ """
+ def get_dated_items(self):
+ """
+ Return (date_list, items, extra_context) for this request.
+ """
+ year = self.get_year()
+ month = self.get_month()
+
+ date_field = self.get_date_field()
+ date = _date_from_string(year, self.get_year_format(),
+ month, self.get_month_format())
+
+ # Construct a date-range lookup.
+ first_day, last_day = _month_bounds(date)
+ lookup_kwargs = {
+ '%s__gte' % date_field: first_day,
+ '%s__lt' % date_field: last_day,
+ }
+
+ qs = self.get_dated_queryset(**lookup_kwargs)
+ date_list = self.get_date_list(qs, 'day')
+
+ return (date_list, qs, {
+ 'month': date,
+ 'next_month': self.get_next_month(date),
+ 'previous_month': self.get_previous_month(date),
+ })
+
+
+
+class MonthArchiveView(MultipleObjectTemplateResponseMixin, BaseMonthArchiveView):
+ """
+ List of objects published in a given year.
+ """
+ template_name_suffix = '_archive_month'
+
+
+class BaseWeekArchiveView(YearMixin, WeekMixin, BaseDateListView):
+ """
+ List of objects published in a given week.
+ """
+
+ def get_dated_items(self):
+ """
+ Return (date_list, items, extra_context) for this request.
+ """
+ year = self.get_year()
+ week = self.get_week()
+
+ date_field = self.get_date_field()
+ date = _date_from_string(year, self.get_year_format(),
+ '0', '%w',
+ week, self.get_week_format())
+
+ # Construct a date-range lookup.
+ first_day = date
+ last_day = date + datetime.timedelta(days=7)
+ lookup_kwargs = {
+ '%s__gte' % date_field: first_day,
+ '%s__lt' % date_field: last_day,
+ }
+
+ qs = self.get_dated_queryset(**lookup_kwargs)
+
+ return (None, qs, {'week': date})
+
+
+class WeekArchiveView(MultipleObjectTemplateResponseMixin, BaseWeekArchiveView):
+ """
+ List of objects published in a given week.
+ """
+ template_name_suffix = '_archive_week'
+
+
+class BaseDayArchiveView(YearMixin, MonthMixin, DayMixin, BaseDateListView):
+ """
+ List of objects published on a given day.
+ """
+ def get_dated_items(self):
+ """
+ Return (date_list, items, extra_context) for this request.
+ """
+ year = self.get_year()
+ month = self.get_month()
+ day = self.get_day()
+
+ date = _date_from_string(year, self.get_year_format(),
+ month, self.get_month_format(),
+ day, self.get_day_format())
+
+ return self._get_dated_items(date)
+
+ def _get_dated_items(self, date):
+ """
+ Do the actual heavy lifting of getting the dated items; this accepts a
+ date object so that TodayArchiveView can be trivial.
+ """
+ date_field = self.get_date_field()
+
+ field = self.get_queryset().model._meta.get_field(date_field)
+ lookup_kwargs = _date_lookup_for_field(field, date)
+
+ qs = self.get_dated_queryset(**lookup_kwargs)
+
+ return (None, qs, {
+ 'day': date,
+ 'previous_day': self.get_previous_day(date),
+ 'next_day': self.get_next_day(date),
+ 'previous_month': self.get_previous_month(date),
+ 'next_month': self.get_next_month(date)
+ })
+
+
+
+class DayArchiveView(MultipleObjectTemplateResponseMixin, BaseDayArchiveView):
+ """
+ List of objects published on a given day.
+ """
+ template_name_suffix = "_archive_day"
+
+
+class BaseTodayArchiveView(BaseDayArchiveView):
+ """
+ List of objects published today.
+ """
+
+ def get_dated_items(self):
+ """
+ Return (date_list, items, extra_context) for this request.
+ """
+ return self._get_dated_items(datetime.date.today())
+
+
+class TodayArchiveView(MultipleObjectTemplateResponseMixin, BaseTodayArchiveView):
+ """
+ List of objects published today.
+ """
+ template_name_suffix = "_archive_day"
+
+
+class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):
+ """
+ Detail view of a single object on a single date; this differs from the
+ standard DetailView by accepting a year/month/day in the URL.
+ """
+ def get_object(self, queryset=None, **kwargs):
+ """
+ Get the object this request displays.
+ """
+ year = self.get_year()
+ month = self.get_month()
+ day = self.get_day()
+ date = _date_from_string(year, self.get_year_format(),
+ month, self.get_month_format(),
+ day, self.get_day_format())
+
+ qs = self.get_queryset()
+
+ if not self.get_allow_future() and date > datetime.date.today():
+ raise Http404("Future %s not available because %s.allow_future is False." % (
+ qs.model._meta.verbose_name_plural, self.__class__.__name__)
+ )
+
+ # Filter down a queryset from self.queryset using the date from the
+ # URL. This'll get passed as the queryset to DetailView.get_object,
+ # which'll handle the 404
+ date_field = self.get_date_field()
+ field = qs.model._meta.get_field(date_field)
+ lookup = _date_lookup_for_field(field, date)
+ qs = qs.filter(**lookup)
+
+ return super(BaseDetailView, self).get_object(queryset=qs, **kwargs)
+
+
+
+class DateDetailView(SingleObjectTemplateResponseMixin, BaseDateDetailView):
+ """
+ Detail view of a single object on a single date; this differs from the
+ standard DetailView by accepting a year/month/day in the URL.
+ """
+ template_name_suffix = '_detail'
+
+
+def _date_from_string(year, year_format, month, month_format, day='', day_format='', delim='__'):
+ """
+ Helper: get a datetime.date object given a format string and a year,
+ month, and possibly day; raise a 404 for an invalid date.
+ """
+ format = delim.join((year_format, month_format, day_format))
+ datestr = delim.join((year, month, day))
+ try:
+ return datetime.date(*time.strptime(datestr, format)[:3])
+ except ValueError:
+ raise Http404(u"Invalid date string '%s' given format '%s'" % (datestr, format))
+
+def _month_bounds(date):
+ """
+ Helper: return the first and last days of the month for the given date.
+ """
+ first_day = date.replace(day=1)
+ if first_day.month == 12:
+ last_day = first_day.replace(year=first_day.year + 1, month=1)
+ else:
+ last_day = first_day.replace(month=first_day.month + 1)
+
+ return first_day, last_day
+
+def _get_next_prev_month(generic_view, naive_result, is_previous, use_first_day):
+ """
+ Helper: Get the next or the previous valid date. The idea is to allow
+ links on month/day views to never be 404s by never providing a date
+ that'll be invalid for the given view.
+
+ This is a bit complicated since it handles both next and previous months
+ and days (for MonthArchiveView and DayArchiveView); hence the coupling to generic_view.
+
+ However in essance the logic comes down to:
+
+ * If allow_empty and allow_future are both true, this is easy: just
+ return the naive result (just the next/previous day or month,
+ reguardless of object existence.)
+
+ * If allow_empty is true, allow_future is false, and the naive month
+ isn't in the future, then return it; otherwise return None.
+
+ * If allow_empty is false and allow_future is true, return the next
+ date *that contains a valid object*, even if it's in the future. If
+ there are no next objects, return None.
+
+ * If allow_empty is false and allow_future is false, return the next
+ date that contains a valid object. If that date is in the future, or
+ if there are no next objects, return None.
+
+ """
+ date_field = generic_view.get_date_field()
+ allow_empty = generic_view.get_allow_empty()
+ allow_future = generic_view.get_allow_future()
+
+ # If allow_empty is True the naive value will be valid
+ if allow_empty:
+ result = naive_result
+
+ # Otherwise, we'll need to go to the database to look for an object
+ # whose date_field is at least (greater than/less than) the given
+ # naive result
+ else:
+ # Construct a lookup and an ordering depending on weather we're doing
+ # a previous date or a next date lookup.
+ if is_previous:
+ lookup = {'%s__lte' % date_field: naive_result}
+ ordering = '-%s' % date_field
+ else:
+ lookup = {'%s__gte' % date_field: naive_result}
+ ordering = date_field
+
+ qs = generic_view.get_queryset().filter(**lookup).order_by(ordering)
+
+ # Snag the first object from the queryset; if it doesn't exist that
+ # means there's no next/previous link available.
+ try:
+ result = getattr(qs[0], date_field)
+ except IndexError:
+ result = None
+
+ # Convert datetimes to a dates
+ if hasattr(result, 'date'):
+ result = result.date()
+
+ # For month views, we always want to have a date that's the first of the
+ # month for consistancy's sake.
+ if result and use_first_day:
+ result = result.replace(day=1)
+
+ # Check against future dates.
+ if result and (allow_future or result < datetime.date.today()):
+ return result
+ else:
+ return None
+
+def _date_lookup_for_field(field, date):
+ """
+ Get the lookup kwargs for looking up a date against a given Field. If the
+ date field is a DateTimeField, we can't just do filter(df=date) because
+ that doesn't take the time into account. So we need to make a range lookup
+ in those cases.
+ """
+ if isinstance(field, models.DateTimeField):
+ date_range = (
+ datetime.datetime.combine(date, datetime.time.min),
+ datetime.datetime.combine(date, datetime.time.max)
+ )
+ return {'%s__range' % field.name: date_range}
+ else:
+ return {field.name: date}
+
142 django/views/generic/detail.py
View
@@ -0,0 +1,142 @@
+import re
+
+from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
+from django.http import Http404
+from django.views.generic.base import TemplateResponseMixin, View
+
+
+class SingleObjectMixin(object):
+ """
+ Provides the ability to retrieve a single object for further manipulation.
+ """
+ model = None
+ queryset = None
+ slug_field = 'slug'
+ context_object_name = None
+
+ def get_object(self, pk=None, slug=None, queryset=None, **kwargs):
+ """
+ Returns the object the view is displaying.
+
+ By default this requires `self.queryset` and a `pk` or `slug` argument
+ in the URLconf, but subclasses can override this to return any object.
+ """
+ # Use a custom queryset if provided; this is required for subclasses
+ # like DateDetailView
+ if queryset is None:
+ queryset = self.get_queryset()
+
+ # Next, try looking up by primary key.
+ if pk is not None:
+ queryset = queryset.filter(pk=pk)
+
+ # Next, try looking up by slug.
+ elif slug is not None:
+ slug_field = self.get_slug_field()
+ queryset = queryset.filter(**{slug_field: slug})
+
+ # If none of those are defined, it's an error.
+ else:
+ raise AttributeError(u"Generic detail view %s must be called with "
+ u"either an object id or a slug."
+ % self.__class__.__name__)
+
+ try:
+ obj = queryset.get()
+ except ObjectDoesNotExist:
+ raise Http404(u"No %s found matching the query" %
+ (queryset.model._meta.verbose_name))
+ return obj
+
+ def get_queryset(self):
+ """
+ Get the queryset to look an object up against. May not be called if
+ `get_object` is overridden.
+ """
+ if self.queryset is None:
+ if self.model:
+ return self.model._default_manager.all()
+ else:
+ raise ImproperlyConfigured(u"%(cls)s is missing a queryset. Define "
+ u"%(cls)s.model, %(cls)s.queryset, or override "
+ u"%(cls)s.get_object()." % {
+ 'cls': self.__class__.__name__
+ })
+ return self.queryset._clone()
+
+ def get_slug_field(self):
+ """
+ Get the name of a slug field to be used to look up by slug.
+ """
+ return self.slug_field
+
+ def get_context_object_name(self, obj):
+ """
+ Get the name to use for the object.
+ """
+ if self.context_object_name:
+ return self.context_object_name
+ elif hasattr(obj, '_meta'):
+ return re.sub('[^a-zA-Z0-9]+', '_',
+ obj._meta.verbose_name.lower())
+ else:
+ return None
+
+ def get_context_data(self, **kwargs):
+ context = kwargs
+ context_object_name = self.get_context_object_name(self.object)
+ if context_object_name:
+ context[context_object_name] = self.object
+ return context
+
+
+class BaseDetailView(SingleObjectMixin, View):
+ def get(self, request, **kwargs):
+ self.object = self.get_object(**kwargs)
+ context = self.get_context_data(object=self.object)
+ return self.render_to_response(context)
+
+
+class SingleObjectTemplateResponseMixin(TemplateResponseMixin):
+ template_name_field = None
+ template_name_suffix = '_detail'
+
+ def get_template_names(self):
+ """
+ Return a list of template names to be used for the request. Must return
+ a list. May not be called if get_template is overridden.
+ """
+ names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
+
+ # If self.template_name_field is set, grab the value of the field
+ # of that name from the object; this is the most specific template
+ # name, if given.
+ if self.object and self.template_name_field:
+ name = getattr(self.object, self.template_name_field, None)
+ if name:
+ names.insert(0, name)
+
+ # The least-specific option is the default <app>/<model>_detail.html;
+ # only use this if the object in question is a model.
+ if hasattr(self.object, '_meta'):
+ names.append("%s/%s%s.html" % (
+ self.object._meta.app_label,
+ self.object._meta.object_name.lower(),
+ self.template_name_suffix
+ ))
+ elif hasattr(self, 'model') and hasattr(self.model, '_meta'):
+ names.append("%s/%s%s.html" % (
+ self.model._meta.app_label,
+ self.model._meta.object_name.lower(),
+ self.template_name_suffix
+ ))
+ return names
+
+
+class DetailView(SingleObjectTemplateResponseMixin, BaseDetailView):
+ """
+ Render a "detail" view of an object.
+
+ By default this is a model instance looked up from `self.queryset`, but the
+ view will support display of *any* object by overriding `self.get_object()`.
+ """
249 django/views/generic/edit.py
View
@@ -0,0 +1,249 @@
+from django.forms import models as model_forms
+from django.core.exceptions import ImproperlyConfigured
+from django.http import HttpResponseRedirect
+from django.views.generic.base import TemplateResponseMixin, View
+from django.views.generic.detail import (SingleObjectMixin,
+ SingleObjectTemplateResponseMixin, BaseDetailView)
+
+
+class FormMixin(object):
+ """
+ A mixin that provides a way to show and handle a form in a request.
+ """
+
+ initial = {}
+ form_class = None
+ success_url = None
+
+ def get_initial(self):
+ """
+ Returns the initial data to use for forms on this view.
+ """
+ return self.initial
+
+ def get_form_class(self):
+ """
+ Returns the form class to use in this view
+ """
+ return self.form_class
+
+ def get_form(self, form_class):
+ """
+ Returns an instance of the form to be used in this view.
+ """
+ if self.request.method in ('POST', 'PUT'):
+ return form_class(
+ self.request.POST,
+ self.request.FILES,
+ initial=self.get_initial()
+ )
+ else:
+ return form_class(
+ initial=self.get_initial()
+ )
+
+ def get_context_data(self, **kwargs):
+ return kwargs
+
+ def get_success_url(self):
+ if self.success_url:
+ url = self.success_url
+ else:
+ raise ImproperlyConfigured(
+ "No URL to redirect to. Either provide a url or define"
+ " a get_absolute_url method on the Model.")
+ return url
+
+ def form_valid(self, form):
+ return HttpResponseRedirect(self.get_success_url())
+
+ def form_invalid(self, form):
+ return self.render_to_response(self.get_context_data(form=form))
+
+
+class ModelFormMixin(FormMixin, SingleObjectMixin):
+ """
+ A mixin that provides a way to show and handle a modelform in a request.
+ """
+
+ def get_form_class(self):
+ """
+ Returns the form class to use in this view
+ """
+ if self.form_class:
+ return self.form_class
+ else:
+ if self.model is None:
+ model = self.queryset.model
+ else:
+ model = self.model
+ return model_forms.modelform_factory(model)
+
+ def get_form(self, form_class):
+ """
+ Returns a form instantiated with the model instance from get_object().
+ """
+ if self.request.method in ('POST', 'PUT'):
+ return form_class(
+ self.request.POST,
+ self.request.FILES,
+ initial=self.get_initial(),
+ instance=self.object,
+ )
+ else:
+ return form_class(
+ initial=self.get_initial(),
+ instance=self.object,
+ )
+
+ def get_success_url(self):
+ if self.success_url:
+ url = self.success_url
+ else:
+ try:
+ url = self.object.get_absolute_url()
+ except AttributeError:
+ raise ImproperlyConfigured(
+ "No URL to redirect to. Either provide a url or define"
+ " a get_absolute_url method on the Model.")
+ return url
+
+ def form_valid(self, form):
+ self.object = form.save()
+ return super(ModelFormMixin, self).form_valid(form)
+
+ def form_invalid(self, form):
+ return self.render_to_response(self.get_context_data(form=form))
+
+ def get_context_data(self, **kwargs):
+ context = kwargs
+ if self.object:
+ context['object'] = self.object
+ context_object_name = self.get_context_object_name(self.object)
+ if context_object_name:
+ context[context_object_name] = self.object
+ return context
+
+
+class ProcessFormView(View):
+ """
+ A mixin that processes a form on POST.
+ """
+ def get(self, request, *args, **kwargs):
+ form_class = self.get_form_class()
+ form = self.get_form(form_class)
+ return self.render_to_response(self.get_context_data(form=form))
+
+ def post(self, request, *args, **kwargs):
+ form_class = self.get_form_class()
+ form = self.get_form(form_class)
+ if form.is_valid():
+ return self.form_valid(form)
+ else:
+ return self.form_invalid(form)
+
+ # PUT is a valid HTTP verb for creating (with a known URL) or editing an
+ # object, note that browsers only support POST for now.
+ put = post
+
+
+class BaseFormView(FormMixin, ProcessFormView):
+ """
+ A base view for displaying a form
+ """
+
+
+class FormView(TemplateResponseMixin, BaseFormView):
+ """
+ A view for displaying a form, and rendering a template response.
+ """
+
+
+class BaseCreateView(ModelFormMixin, ProcessFormView):
+ """
+ Base view for creating an new object instance.
+
+ Using this base class requires subclassing to provide a response mixin.
+ """
+ def get(self, request, *args, **kwargs):
+ self.object = None
+ return super(BaseCreateView, self).get(request, *args, **kwargs)
+
+ def post(self, request, *args, **kwargs):
+ self.object = None
+ return super(BaseCreateView, self).post(request, *args, **kwargs)
+
+ # PUT is a valid HTTP verb for creating (with a known URL) or editing an
+ # object, note that browsers only support POST for now.
+ put = post
+
+class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView):
+ """
+ View for creating an new object instance,
+ with a response rendered by template.
+ """
+ template_name_suffix = '_form'
+
+
+class BaseUpdateView(ModelFormMixin, ProcessFormView):
+ """
+ Base view for updating an existing object.
+
+ Using this base class requires subclassing to provide a response mixin.
+ """
+ def get(self, request, *args, **kwargs):
+ self.object = self.get_object(**kwargs)
+ return super(BaseUpdateView, self).get(request, *args, **kwargs)
+
+ def post(self, request, *args, **kwargs):
+ self.object = self.get_object(**kwargs)
+ return super(BaseUpdateView, self).post(request, *args, **kwargs)
+
+ # PUT is a valid HTTP verb for creating (with a known URL) or editing an
+ # object, note that browsers only support POST for now.
+ put = post
+
+
+class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView):
+ """
+ View for updating an object,
+ with a response rendered by template..
+ """
+ template_name_suffix = '_form'
+
+
+class DeletionMixin(object):
+ """
+ A mixin providing the ability to delete objects
+ """
+ success_url = None
+
+ def delete(self, request, *args, **kwargs):
+ self.object = self.get_object(**kwargs)
+ self.object.delete()
+ return HttpResponseRedirect(self.get_success_url())
+
+ # Add support for browsers which only accept GET and POST for now.
+ post = delete
+
+ def get_success_url(self):
+ if self.success_url:
+ return self.success_url
+ else:
+ raise ImproperlyConfigured(
+ "No URL to redirect to. Either provide a url or define"
+ " a get_absolute_url method on the Model.")
+
+class BaseDeleteView(DeletionMixin, BaseDetailView):
+ """
+ Base view for deleting an object.
+
+ Using this base class requires subclassing to provide a response mixin.
+ """
+
+class DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView):
+ """
+ View for deleting an object retrieved with `self.get_object()`,
+ with a response rendered by template.
+ """
+ template_name_suffix = '_confirm_delete'
138 django/views/generic/list.py
View
@@ -0,0 +1,138 @@
+from django.core.paginator import Paginator, InvalidPage
+from django.core.exceptions import ImproperlyConfigured
+from django.http import Http404
+from django.utils.encoding import smart_str
+from django.views.generic.base import TemplateResponseMixin, View
+
+class MultipleObjectMixin(object):
+ allow_empty = True
+ queryset = None
+ model = None
+ paginate_by = None
+ context_object_name = None
+
+ def get_queryset(self):
+ """
+ Get the list of items for this view. This must be an interable, and may
+ be a queryset (in which qs-specific behavior will be enabled).
+ """
+ if self.queryset is not None:
+ queryset = self.queryset
+ if hasattr(queryset, '_clone'):
+ queryset = queryset._clone()
+ elif self.model is not None:
+ queryset = self.model._default_manager.all()
+ else:
+ raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'"
+ % self.__class__.__name__)
+ return queryset
+
+ def paginate_queryset(self, queryset, page_size):
+ """
+ Paginate the queryset, if needed.
+ """
+ if queryset.count() > page_size:
+ paginator = Paginator(queryset, page_size, allow_empty_first_page=self.get_allow_empty())
+ page = self.kwargs.get('page', None) or self.request.GET.get('page', 1)
+ try:
+ page_number = int(page)
+ except ValueError:
+ if page == 'last':
+ page_number = paginator.num_pages
+ else:
+ raise Http404("Page is not 'last', nor can it be converted to an int.")
+ try:
+ page = paginator.page(page_number)
+ return (paginator, page, page.object_list, True)
+ except InvalidPage:
+ raise Http404(u'Invalid page (%s)' % page_number)
+ else:
+ return (None, None, queryset, False)
+
+ def get_paginate_by(self, queryset):
+ """
+ Get the number of items to paginate by, or ``None`` for no pagination.
+ """
+ return self.paginate_by
+
+ def get_allow_empty(self):
+ """
+ Returns ``True`` if the view should display empty lists, and ``False``
+ if a 404 should be raised instead.
+ """
+ return self.allow_empty
+
+ def get_context_object_name(self, object_list):
+ """
+ Get the name of the item to be used in the context.
+ """
+ if self.context_object_name:
+ return self.context_object_name
+ elif hasattr(object_list, 'model'):
+ return smart_str(object_list.model._meta.verbose_name_plural)
+ else:
+ return None
+
+ def get_context_data(self, **kwargs):
+ """
+ Get the context for this view.
+ """
+ queryset = kwargs.get('object_list')
+ page_size = self.get_paginate_by(queryset)
+ if page_size:
+ paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
+ context = {
+ 'paginator': paginator,
+ 'page_obj': page,
+ 'is_paginated': is_paginated,
+ 'object_list': queryset
+ }
+ else:
+ context = {
+ 'paginator': None,
+ 'page_obj': None,
+ 'is_paginated': False,
+ 'object_list': queryset
+ }
+ context.update(kwargs)
+ context_object_name = self.get_context_object_name(queryset)
+ if context_object_name is not None:
+ context[context_object_name] = queryset
+ return context
+
+
+class BaseListView(MultipleObjectMixin, View):
+ def get(self, request, *args, **kwargs):
+ self.object_list = self.get_queryset()
+ allow_empty = self.get_allow_empty()
+ if not allow_empty and len(self.object_list) == 0:
+ raise Http404(u"Empty list and '%s.allow_empty' is False."
+ % self.__class__.__name__)
+ context = self.get_context_data(object_list=self.object_list)
+ return self.render_to_response(context)
+
+class MultipleObjectTemplateResponseMixin(TemplateResponseMixin):
+ template_name_suffix = '_list'
+
+ def get_template_names(self):
+ """
+ Return a list of template names to be used for the request. Must return
+ a list. May not be called if get_template is overridden.
+ """
+ names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
+
+ # If the list is a queryset, we'll invent a template name based on the
+ # app and model name. This name gets put at the end of the template
+ # name list so that user-supplied names override the automatically-
+ # generated ones.
+ if hasattr(self.object_list, 'model'):
+ opts = self.object_list.model._meta
+ names.append("%s/%s%s.html" % (opts.app_label, opts.object_name.lower(), self.template_name_suffix))
+
+ return names
+
+class ListView(MultipleObjectTemplateResponseMixin, BaseListView):
+ """
+ Render some list of objects, set by `self.model` or `self.queryset`.
+ `self.queryset` can actually be any iterable of items, not just a queryset.
+ """
7 django/views/generic/list_detail.py
View
@@ -4,6 +4,13 @@
from django.core.paginator import Paginator, InvalidPage
from django.core.exceptions import ObjectDoesNotExist
+import warnings
+warnings.warn(
+ 'Function-based generic views have been deprecated; use class-based views instead.',
+ PendingDeprecationWarning
+)
+
+
def object_list(request, queryset, paginate_by=None, page=None,
allow_empty=True, template_name=None, template_loader=loader,
extra_context=None, context_processors=None, template_object_name='object',
6 django/views/generic/simple.py
View
@@ -2,6 +2,12 @@
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponseGone
from django.utils.log import getLogger
+import warnings
+warnings.warn(
+ 'Function-based generic views have been deprecated; use class-based views instead.',
+ PendingDeprecationWarning
+)
+
logger = getLogger('django.request')
6 docs/index.txt
View
@@ -103,8 +103,8 @@ The view layer
:doc:`Custom storage <howto/custom-file-storage>`
* **Generic views:**
- :doc:`Overview<topics/generic-views>` |
- :doc:`Built-in generic views<ref/generic-views>`
+ :doc:`Overview<topics/class-based-views>` |
+ :doc:`Built-in generic views<ref/class-based-views>`
* **Advanced:**
:doc:`Generating CSV <howto/outputting-csv>` |
@@ -189,6 +189,8 @@ Other batteries included
* :doc:`Unicode in Django <ref/unicode>`
* :doc:`Web design helpers <ref/contrib/webdesign>`
* :doc:`Validators <ref/validators>`
+ * Function-based generic views (Deprecated) :doc:`Overview<topics/generic-views>` | :doc:`Built-in generic views<ref/generic-views>` | :doc:`Migration guide<topics/generic-views-migration>`
+
The Django open-source project
==============================
9 docs/internals/deprecation.txt
View
@@ -118,6 +118,15 @@ their deprecation, as per the :ref:`Django deprecation policy
:func:`django.contrib.formtools.utils.security_hash`
is deprecated, in favour of :func:`django.contrib.formtools.utils.form_hmac`
+ * The function-based generic views have been deprecated in
+ favor of their class-based cousins. The following modules
+ will be removed:
+
+ * :mod:`django.views.generic.create_update`
+ * :mod:`django.views.generic.date_based`
+ * :mod:`django.views.generic.list_detail`
+ * :mod:`django.views.generic.simple`
+
* 2.0
* ``django.views.defaults.shortcut()``. This function has been moved
to ``django.contrib.contenttypes.views.shortcut()`` as part of the
158 docs/intro/tutorial04.txt
View
@@ -232,6 +232,7 @@ tutorial so far::
Change it like so::
from django.conf.urls.defaults import *
+ from django.views.generic import DetailView, ListView
from polls.models import Poll
info_dict = {
@@ -239,88 +240,91 @@ Change it like so::
}
urlpatterns = patterns('',
- (r'^$', 'django.views.generic.list_detail.object_list', info_dict),
- (r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
- url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
+ (r'^$',
+ ListView.as_view(
+ models=Poll,
+ context_object_name='latest_poll_list'
+ template_name='polls/index.html')),
+ (r'^(?P<pk>\d+)/$',
+ DetailView.as_view(
+ models=Poll,
+ template_name='polls/detail.html')),
+ url(r'^(?P<pk>\d+)/results/$',
+ DetailView.as_view(
+ models=Poll,
+ template_name='polls/results.html'),
+ 'poll_results'),
(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
)
We're using two generic views here:
-:func:`~django.views.generic.list_detail.object_list` and
-:func:`~django.views.generic.list_detail.object_detail`. Respectively, those two
-views abstract the concepts of "display a list of objects" and "display a detail
-page for a particular type of object."
-
- * Each generic view needs to know what data it will be acting upon. This
- data is provided in a dictionary. The ``queryset`` key in this dictionary
- points to the list of objects to be manipulated by the generic view.
-
- * The :func:`~django.views.generic.list_detail.object_detail` generic view
- expects the ID value captured from the URL to be called ``"object_id"``,
- so we've changed ``poll_id`` to ``object_id`` for the generic views.
-
- * We've added a name, ``poll_results``, to the results view so that we have
- a way to refer to its URL later on (see the documentation about
- :ref:`naming URL patterns <naming-url-patterns>` for information). We're
- also using the :func:`~django.conf.urls.default.url` function from
+:class:`~django.views.generic.list.ListView` and
+:class:`~django.views.generic.detail.DetailView`. Respectively, those
+two views abstract the concepts of "display a list of objects" and
+"display a detail page for a particular type of object."
+
+ * Each generic view needs to know what model it will be acting
+ upon. This is provided using the ``model`` parameter.
+
+ * The :class:`~django.views.generic.list.DetailView` generic view
+ expects the primary key value captured from the URL to be called
+ ``"pk"``, so we've changed ``poll_id`` to ``pk`` for the generic
+ views.
+
+ * We've added a name, ``poll_results``, to the results view so
+ that we have a way to refer to its URL later on (see the
+ documentation about :ref:`naming URL patterns
+ <naming-url-patterns>` for information). We're also using the
+ :func:`~django.conf.urls.default.url` function from
:mod:`django.conf.urls.defaults` here. It's a good habit to use
- :func:`~django.conf.urls.defaults.url` when you are providing a pattern
- name like this.
-
-By default, the :func:`~django.views.generic.list_detail.object_detail` generic
-view uses a template called ``<app name>/<model name>_detail.html``. In our
-case, it'll use the template ``"polls/poll_detail.html"``. Thus, rename your
-``polls/detail.html`` template to ``polls/poll_detail.html``, and change the
-:func:`~django.shortcuts.render_to_response` line in ``vote()``.
-
-Similarly, the :func:`~django.views.generic.list_detail.object_list` generic
-view uses a template called ``<app name>/<model name>_list.html``. Thus, rename
-``polls/index.html`` to ``polls/poll_list.html``.
-
-Because we have more than one entry in the URLconf that uses
-:func:`~django.views.generic.list_detail.object_detail` for the polls app, we
-manually specify a template name for the results view:
-``template_name='polls/results.html'``. Otherwise, both views would use the same
-template. Note that we use ``dict()`` to return an altered dictionary in place.
-
-.. note:: :meth:`django.db.models.QuerySet.all` is lazy
-
- It might look a little frightening to see ``Poll.objects.all()`` being used
- in a detail view which only needs one ``Poll`` object, but don't worry;
- ``Poll.objects.all()`` is actually a special object called a
- :class:`~django.db.models.QuerySet`, which is "lazy" and doesn't hit your
- database until it absolutely has to. By the time the database query happens,
- the :func:`~django.views.generic.list_detail.object_detail` generic view
- will have narrowed its scope down to a single object, so the eventual query
- will only select one row from the database.
-
- If you'd like to know more about how that works, The Django database API
- documentation :ref:`explains the lazy nature of QuerySet objects
- <querysets-are-lazy>`.
-
-In previous parts of the tutorial, the templates have been provided with a
-context that contains the ``poll`` and ``latest_poll_list`` context variables.
-However, the generic views provide the variables ``object`` and ``object_list``
-as context. Therefore, you need to change your templates to match the new
-context variables. Go through your templates, and modify any reference to
-``latest_poll_list`` to ``object_list``, and change any reference to ``poll``
-to ``object``.
-
-You can now delete the ``index()``, ``detail()`` and ``results()`` views
-from ``polls/views.py``. We don't need them anymore -- they have been replaced
-by generic views.
-
-The ``vote()`` view is still required. However, it must be modified to match the
-new context variables. In the :func:`~django.shortcuts.render_to_response` call,
-rename the ``poll`` context variable to ``object``.
-
-The last thing to do is fix the URL handling to account for the use of generic
-views. In the vote view above, we used the
-:func:`~django.core.urlresolvers.reverse` function to avoid hard-coding our
-URLs. Now that we've switched to a generic view, we'll need to change the
-:func:`~django.core.urlresolvers.reverse` call to point back to our new generic
-view. We can't simply use the view function anymore -- generic views can be (and
-are) used multiple times -- but we can use the name we've given::
+ :func:`~django.conf.urls.defaults.url` when you are providing a
+ pattern name like this.
+
+By default, the :class:`~django.views.generic.list.DetailView` generic
+view uses a template called ``<app name>/<model name>_detail.html``.
+In our case, it'll use the template ``"polls/poll_detail.html"``. The
+``template_name`` argument is used to tell Django to use a specific
+template name instead of the autogenerated default template name. We
+also specify the ``template_name`` for the ``results`` list view --
+this ensures that the results view and the detail view have a
+different appearance when rendered, even though they're both a
+:class:`~django.views.generic.list.DetailView` behind the scenes.
+
+Similarly, the :class:`~django.views.generic.list.ListView` generic
+view uses a default template called ``<app name>/<model
+name>_list.html``; we use ``template_name`` to tell
+:class:`~django.views.generic.list.ListView` to use our existing
+``"polls/index.html"`` template.
+
+In previous parts of the tutorial, the templates have been provided
+with a context that contains the ``poll`` and ``latest_poll_list``
+context variables. For DetailView the ``poll`` variable is provided
+automatically -- since we're using a Django model (``Poll``), Django
+is able to determine an appropriate name for the context variable.
+However, for ListView, the automatically generated context variable is
+``poll_list``. To override this we provide the ``context_object_name``
+option, specifying that we want to use ``latest_poll_list`` instead.
+As an alternative approach, you could change your templates to match
+the new default context variables -- but it's a lot easier to just
+tell Django to use the variable you want.
+
+You can now delete the ``index()``, ``detail()`` and ``results()``
+views from ``polls/views.py``. We don't need them anymore -- they have
+been replaced by generic views.
+
+The ``vote()`` view is still required. However, it must be modified to
+match the new context variables. In the
+:func:`~django.shortcuts.render_to_response` call, rename the ``poll``
+context variable to ``object``.
+
+The last thing to do is fix the URL handling to account for the use of
+generic views. In the vote view above, we used the
+:func:`~django.core.urlresolvers.reverse` function to avoid
+hard-coding our URLs. Now that we've switched to a generic view, we'll
+need to change the :func:`~django.core.urlresolvers.reverse` call to
+point back to our new generic view. We can't simply use the view
+function anymore -- generic views can be (and are) used multiple times
+-- but we can use the name we've given::
return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
1,391 docs/ref/class-based-views.txt
View
@@ -0,0 +1,1391 @@
+=========================
+Class-Based Generic views
+=========================
+
+.. versionadded:: 1.3
+
+.. note::
+ Prior to Django 1.3, generic views were implemented as functions. The
+ function-based implementation has been deprecated in favor of the
+ class-based approach described here.
+
+ For the reference to the old on details on the old implementation,
+ see the :doc:`topic guide </topics/generic-views>` and
+ :doc:`detailed reference </topics/generic-views>`.
+
+Writing Web applications can be monotonous, because we repeat certain patterns
+again and again. In Django, the most common of these patterns have been
+abstracted into "generic views" that let you quickly provide common views of
+an object without actually needing to write any Python code.
+
+A general introduction to generic views can be found in the :doc:`topic guide
+</topics/class-based-views>`.
+
+This reference contains details of Django's built-in generic views, along with
+a list of all keyword arguments that a generic view expects. Remember that
+arguments may either come from the URL pattern or from the ``extra_context``
+additional-information dictionary.
+
+Most generic views require the ``queryset`` key, which is a ``QuerySet``
+instance; see :doc:`/topics/db/queries` for more information about ``QuerySet``
+objects.
+
+Mixins
+======
+
+A mixin class is a way of using the inheritance capabilities of
+classes to compose a class out of smaller pieces of behavior. Django's
+class-based generic views are constructed by composing a mixins into
+usable generic views.
+
+For example, the :class:`~django.views.generic.base.detail.DetailView`
+is composed from:
+
+ * :class:`~django.db.views.generic.base.View`, which provides the
+ basic class-based behavior
+ * :class:`~django.db.views.generic.detail.SingleObjectMixin`, which
+ provides the utilities for retrieving and displaying a single object
+ * :class:`~django.db.views.generic.detail.SingleObjectTemplateResponseMixin`,
+ which provides the tools for rendering a single object into a
+ template-based response.
+
+When combined, these mixins provide all the pieces necessary to
+provide a view over a single object that renders a template to produce
+a response.
+
+When the documentation for a view gives the list of mixins, that view
+inherits all the properties and methods of that mixin.
+
+Django provides a range of mixins. If you want to write your own
+generic views, you can build classes that compose these mixins in
+interesting ways. Alternatively, you can just use the pre-mixed
+`Generic views`_ that Django provides.
+
+Simple mixins
+-------------
+
+.. currentmodule:: django.views.generic.base
+
+TemplateResponseMixin
+~~~~~~~~~~~~~~~~~~~~~
+.. class:: TemplateResponseMixin()
+
+**Attributes**
+
+.. attribute:: TemplateResponseMixin.template_name
+
+ The path to the template to use when rendering the view.
+
+**Methods**
+
+.. method:: TemplateResponseMixin.render_to_response(context)
+
+ Returns a full composed HttpResponse instance, ready to be
+ returned to the user.
+
+ Calls, :meth:`~TemplateResponseMixin.render_template()` to build
+ the content of the response, and
+ :meth:`~TemplateResponseMixin.get_response()` to construct the
+ :class:`~django.http.HttpResponse` object.
+
+.. method:: TemplateResponseMixin.get_response(content, **httpresponse_kwargs)
+
+ Constructs the :class:`~django.http.HttpResponse` object around
+ the given content. If any keyword arguments are provided, they
+ will be passed to the constructor of the
+ :class:`~django.http.HttpResponse` instance.
+
+.. method:: TemplateResponseMixin.render_template(context)
+
+ Calls :meth:`~TemplateResponseMixin.get_context_instance()` to
+ obtain the :class:`Context` instance to use for rendering, and
+ calls :meth:`TemplateReponseMixin.get_template()` to load the
+ template that will be used to render the final content.
+
+.. method:: TemplateResponseMixin.get_context_instance(context)
+
+ Turns the data dictionary ``context`` into an actual context
+ instance that can be used for rendering.
+
+ By default, constructs a :class:`~django.template.RequestContext`
+ instance.
+
+.. method:: TemplateResponseMixin.get_template()
+
+ Calls :meth:`~TemplateResponseMixin.get_template_names()` to
+ obtain the list of template names that will be searched looking
+ for an existent template.
+
+.. method:: TemplateResponseMixin.get_template_names()
+
+ The list of template names to search for when rendering the
+ template.
+
+ If :attr:`TemplateResponseMixin.template_name` is specified, the
+ default implementation will return a list containing
+ :attr:`TemplateResponseMixin.template_name` (if it is specified).
+
+.. method:: TemplateResponseMixin.load_template(names)
+
+ Loads and returns a template found by searching the list of
+ ``names`` for a match. Uses Django's default template loader.
+
+Single object mixins
+--------------------
+
+.. currentmodule:: django.views.generic.detail
+
+SingleObjectMixin
+~~~~~~~~~~~~~~~~~
+.. class:: SingleObjectMixin()
+
+**Attributes**
+
+.. attribute:: SingleObjectMixin.model
+
+ The model that this view will display data for. Specifying ``model
+ = Foo`` is effectively the same as specifying ``queryset =
+ Foo.objects.all()``.
+
+.. attribute:: SingleObjectMixin.queryset
+
+ A ``QuerySet`` that represents the objects. If provided, the
+ value of :attr:`SingleObjectMixin.queryset` supersedes the
+ value provided for :attr:`SingleObjectMixin.model`.
+
+.. attribute:: SingleObjectMixin.slug_field
+
+ The name of the field on the model that contains the slug. By
+ default, ``slug_field`` is ``'slug'``.
+
+.. attribute:: SingleObjectMixin.context_object_name
+
+ Designates the name of the variable to use in the context.
+
+**Methods**
+
+.. method:: SingleObjectMixin.get_queryset()
+
+ Returns the queryset that will be used to retrieve the object that
+ this view will display.
+
+.. method:: SingleObjectMixin.get_context_object_name(object_list)
+
+ Return the context variable name that will be used to contain the
+ list of data that this view is manipulating. If object_list is a
+ queryset of Django objects, the context name will be verbose
+ plural name of the model that the queryset is composed from.
+
+.. method:: SingleObjectMixin.get_context_data(**kwargs)
+
+ Returns context data for displaying the list of objects.
+
+**Context**
+
+ * ``object``: The object that this view is displaying. If
+ ``context_object_name`` is specified, that variable will also be
+ set in the context, with the same value as ``object``.
+
+SingleObjectTemplateResponseMixin
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. class:: SingleObjectTemplateResponseMixin()
+
+A mixin class that performs template-based response rendering for
+views that operate upon a single object instance. Requires that the
+view it is mixed with provides ``self.object``, the object instance
+that the view is operating on. ``self.object`` will usually be, but is
+not required to be, an instance of a Django model. It may be ``None``
+if the view is in the process of constructing a new instance.
+
+**Extends**
+
+ * :class:`~django.views.generic.base.TemplateResponseMixin`
+
+**Attributes**
+
+.. attribute:: SingleObjectTemplateResponseMixin.template_name_field
+
+ The field on the current object instance that can be used to
+ determine the name of a candidate template. If either
+ ``template_name_field`` or the value of the
+ ``template_name_field`` on the current object instance is
+ ``None``, the object will not be interrogated for a candidate
+ template name.
+
+.. attribute:: SingleObjectTemplateResponseMixin.template_name_suffix
+
+ The suffix to append to the auto-generated candidate template name.
+ Default suffix is ``_detail``.
+
+**Methods**
+
+.. method:: SingleObjectTemplateResponseMixin.get_template_names()
+
+ Returns a list of candidate template names. Returns the following
+ list:
+
+ * the value of ``template_name`` on the view (if provided)
+ * the contents of the ``template_name_field`` field on the
+ object instance that the view is operating upon (if available)
+ * ``<app_label>/<object_name><template_name_suffix>.html``
+
+Multiple object mixins
+----------------------
+
+.. currentmodule:: django.views.generic.list
+
+MultipleObjectMixin
+~~~~~~~~~~~~~~~~~~~
+.. class:: MultipleObjectMixin()
+
+A mixin that can be used to display a list of objects.
+
+If ``paginate_by`` is specified, Django will paginate the results
+returned by this. You can specify the page number in the URL in one of
+two ways:
+
+ * Use the ``page`` parameter in the URLconf. For example, this is
+ what your URLconf might look like::
+
+ (r'^objects/page(?P<page>[0-9]+)/$', PaginatedView.as_view())
+
+ * Pass the page number via the ``page`` query-string parameter. For
+ example, a URL would look like this::
+
+ /objects/?page=3
+
+These values and lists are 1-based, not 0-based, so the first page
+would be represented as page ``1``.
+
+For more on pagination, read the :doc:`pagination documentation
+</topics/pagination>`.
+
+As a special case, you are also permitted to use ``last`` as a value
+for ``page``::
+
+ /objects/?page=last
+
+This allows you to access the final page of results without first
+having to determine how many pages there are.
+
+Note that ``page`` *must* be either a valid page number or the value
+``last``; any other value for ``page`` will result in a 404 error.
+
+**Attributes**
+
+.. attribute:: MultipleObjectMixin.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 instead of displaying an empty page. By
+ default, this is ``True``.
+
+.. attribute:: MultipleObjectMixin.model
+
+ The model that this view will display data for. Specifying ``model
+ = Foo`` is effectively the same as specifying ``queryset =
+ Foo.objects.all()``.
+
+.. attribute:: MultipleObjectMixin.queryset
+
+ A ``QuerySet`` that represents the objects. If provided, the
+ value of :attr:`MultipleObjectMixin.queryset` supersedes the
+ value provided for :attr:`MultipleObjectMixin.model`.
+
+.. attribute:: MultipleObjectMixin.paginate_by
+
+ An integer specifying how many objects should be displayed per
+ page. If this is given, the view will paginate objects with
+ :attr:`MultipleObjectMixin.paginate_by` objects per page. The view
+ will expect either a ``page`` query string parameter (via ``GET``)
+ or a ``page`` variable specified in the URLconf.
+
+.. attribute:: MultipleObjectMixin.context_object_name
+
+ Designates the name of the variable to use in the context.
+
+**Methods**
+
+.. method:: MultipleObjectMixin.get_queryset()
+
+ Returns the queryset that represents the data this view will display.
+
+.. method:: MultipleObjectMixin.paginate_queryset(queryset, page_size)
+
+ Returns a 4-tuple containing::
+
+ (``paginator``, ``page``, ``object_list``, ``is_paginated``)
+
+ constructed by paginating ``queryset`` into pages of size ``page_size``.
+ If the request contains a ``page`` argument, either as a captured
+ URL argument or as a GET argument, ``object_list`` will correspond
+ to the objects from that page.
+
+.. method:: MultipleObjectMixin.get_paginate_by(queryset)
+
+.. method:: MultipleObjectMixin.get_allow_empty()
+
+ Return a boolean specifying whether to display the page if no objects are
+ available. If this method returns ``False`` and no objects are available, the
+ view will raise a 404 instead of displaying an empty page. By
+ default, this is ``True``.
+
+.. method:: MultipleObjectMixin.get_context_object_name(object_list)
+
+ Return the context variable name that will be used to contain the
+ list of data that this view is manipulating. If object_list is a
+ queryset of Django objects, the context name will be verbose
+ plural name of the model that the queryset is composed from.
+
+.. method:: MultipleObjectMixin.get_context_data(**kwargs)
+
+ Returns context data for displaying the list of objects.
+
+**Context**
+
+ * ``object_list``: The list of object that this view is
+ displaying. If ``context_object_name`` is specified, that
+ variable will also be set in the context, with the same value as
+ ``object_list``.
+
+ * ``is_paginated``: A boolean representing whether the results are
+ paginated. Specifically, this is set to ``False`` if no page
+ size has been specified, or if the number of available objects
+ is less than or equal to ``paginate_by``.
+
+ * ``paginator``: An instance of
+ :class:`django.core.paginator.Paginator`. If the page is not
+ paginated, this context variable will be ``None``
+
+ * ``page_obj``: An instance of
+ :class:`django.core.paginator.Page`. If the page is not
+ paginated, this context variable will be ``None``
+
+MultipleObjectTemplateResponseMixin
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. class:: MultipleObjectTemplateResponseMixin()
+
+A mixin class that performs template-based response rendering for
+views that operate upon a list of object instances. Requires that the
+view it is mixed with provides ``self.object_list``, the list of
+object instances that the view is operating on. ``self.object_list``
+may be, but is not required to be, a
+:class:`~django.db.models.Queryset`.
+
+**Extends**
+
+ * :class:`~django.views.generic.base.TemplateResponseMixin`
+
+**Attributes**
+
+.. attribute:: MultipleObjectTemplateResponseMixin.template_name_suffix
+
+ The suffix to append to the auto-generated candidate template name.
+ Default suffix is ``_list``.
+
+**Methods**
+
+.. method:: MultipleObjectTemplateResponseMixin.get_template_names()
+
+ Returns a list of candidate template names. Returns the following
+ list:
+
+ * the value of ``template_name`` on the view (if provided)
+ * ``<app_label>/<object_name><template_name_suffix>.html``
+
+Editing mixins
+--------------
+
+.. currentmodule:: django.views.generic.edit
+
+FormMixin
+~~~~~~~~~
+.. class:: FormMixin()
+
+A mixin class that provides facilities for creating and displaying forms.
+
+**Attributes**
+
+.. attribute:: FormMixin.initial
+
+ A dictionary containing initial data for the form.
+
+.. attribute:: FormMixin.form_class
+
+ The form class to instantiate.
+
+.. attribute:: FormMixin.success_url
+
+ The URL to redirect to when the form is successfully processed.
+
+**Methods**
+
+.. method:: FormMixin.get_initial()
+
+ Retrieve initial data for the form. By default, returns
+ :attr:`FormMixin.initial`.
+
+.. method:: FormMixin.get_form_class()
+
+ Retrieve the form class to instantiate. By default,
+ :attr:`FormMixin.form_class`.
+
+.. method:: FormMixin.get_form(form_class)
+
+ Instantiate an instance of ``form_class``. If the request is a
+ ``POST`` or ``PUT``, the request data (``request.POST`` and
+ ``request.FILES``) will be provided to the form at time of
+ construction
+
+.. method:: FormMixin.get_success_url()
+
+ Determine the URL to redirect to when the form is successfully
+ validated. Returns :attr:`FormMixin.success_url` by default.
+
+.. method:: FormMixin.form_valid()
+
+ Redirects to :attr:`ModelFormMixin.success_url`.
+
+.. method:: FormMixin.form_invalid()
+
+ Renders a response, providing the invalid form as context.
+
+.. method:: FormMixin.get_context_data(**kwargs)
+
+ Populates a context containing the contents of ``kwargs``.
+
+**Context**
+
+ * ``form``: The form instance that was generated for the view.
+
+**Notes**
+
+ * Views mixing :class:`~django.views.generic.edit.FormMixin` must
+ provide an implementation of :meth:`~FormMixin.form_valid()` and
+ :meth:`~FormMixin.form_invalid()`.
+
+ModelFormMixin
+~~~~~~~~~~~~~~
+.. class:: ModelFormMixin()
+
+A form mixin that works on ModelForms, rather than a standalone form.
+
+Since this is a subclass of
+:class:`~django.views.generic.detail.SingleObjectMixin`, instances of
+this mixin have access to the :attr:`~SingleObjectMixin.model`` and
+:attr:`~SingleObjectMixin.queryset`` attributes, describing the type of
+object that the ModelForm is manipulating. The view also provides
+``self.object``, the instance being manipulated. If the instance is
+being created, ``self.object`` will be ``None``
+
+**Mixins**
+
+ * :class:`django.views.generic.forms.FormMixin`
+ * :class:`django.views.generic.detail.SingleObjectMixin`
+
+**Attributes**
+
+.. attribute:: ModelFormMixin.success_url
+
+ The URL to redirect to when the form is successfully processed.
+
+**Methods**
+
+.. method:: ModelFormMixin.get_form_class()
+
+ Retrieve the form class to instantiate. If
+ :attr:`FormMixin.form_class` is provided, that class will be used.
+ Otherwise, a ModelForm will be instantiated using the model
+ associated with the :attr:`~SingleObjectMixin.queryset``, or with
+ the :attr:`~SingleObjectMixin.model``, depending on which
+ attribute is provided.
+
+.. method:: FormMixin.get_form(form_class)
+
+ Instantiate an instance of ``form_class``. If the request is a
+ ``POST`` or ``PUT``, the request data (``request.POST`` and
+ ``request.FILES``) will be provided to the form at time of
+ construction. The current instance (``self.object``) will also
+ be provided.
+
+.. method:: ModelFormMixin.get_success_url()
+
+ Determine the URL to redirect to when the form is successfully
+ validated. Returns :attr:`FormMixin.success_url` if it is
+ provided; otherwise, attempts to use the ``get_absolute_url()``
+ of the object.
+
+.. method:: ModelFormMixin.form_valid()
+
+ Saves the form instance, sets the current object for the view,
+ and redirects to :attr:`ModelFormMixin.success_url`.
+
+.. method:: ModelFormMixin.form_invalid()
+
+ Renders a response, providing the invalid form as context.
+
+ProcessFormView
+~~~~~~~~~~~~~~~
+.. class:: ProcessFormView()
+
+A mixin that provides basic HTTP GET and POST workflow.
+
+On GET:
+ * Construct a form
+ * Render a response using a context that contains that form
+
+On POST:
+ * Construct a form
+ * Check the form for validity, and handle accordingly.
+
+The PUT action is also handled, as an analog of POST.
+
+DeletionMixin
+~~~~~~~~~~~~~
+.. class:: DeletionMixin()
+
+Enables handling of the ``DELETE`` http action.
+
+**Attributes**
+
+.. attribute:: DeletionMixin.success_url
+
+ The url to redirect to when the nominated object has been
+ successfully deleted.
+
+**Methods**
+
+.. attribute:: DeletionMixin.get_success_url(obj)
+
+ Returns the url to redirect to when the nominated object has been
+ successfully deleted. Returns
+ :attr:`~django.views.generic.edit.DeletionMixin.success_url` by
+ default.
+
+Date-based mixins
+-----------------
+
+.. currentmodule:: django.views.generic.dates
+
+YearMixin
+~~~~~~~~~
+.. class:: YearMixin()
+
+A mixin that can be used to retrieve and provide parsing information
+for a year component of a date.
+
+**Attributes**
+
+.. attribute:: YearMixin.year_format
+
+ The strftime_ format to use when parsing the year. By default,
+ this is ``'%Y'``.
+
+.. _strftime: http://docs.python.org/library/time.html#time.strftime
+
+.. attribute:: YearMixin.year
+
+ **Optional** The value for the year (as a string). By default,
+ set to ``None``, which means the year will be determined using
+ other means.
+
+**Methods**
+
+.. method:: YearMixin.get_year_format()
+
+ Returns the strftime_ format to use when parsing the year. Returns
+ :attr:`YearMixin.year_format` by default.
+
+.. method:: YearMixin.get_year()
+
+ Returns the year for which this view will display data. Tries the
+ following sources, in order:
+
+ * The value of the :attr:`YearMixin.year` attribute.
+ * The value of the `year` argument captured in the URL pattern
+ * The value of the `year` GET query argument.
+
+ Raises a 404 if no valid year specification can be found.
+
+MonthMixin
+~~~~~~~~~~
+.. class:: MonthMixin()
+
+A mixin that can be used to retrieve and provide parsing information
+for a month component of a date.
+
+**Attributes**
+
+.. attribute:: MonthMixin.month_format
+
+ The strftime_ format to use when parsing the month. By default,
+ this is ``'%b'``.
+
+.. attribute:: MonthMixin.month
+
+ **Optional** The value for the month (as a string). By default,
+ set to ``None``, which means the month will be determined using
+ other means.
+
+**Methods**
+
+.. method:: MonthMixin.get_month_format()
+
+ Returns the strftime_ format to use when parsing the month. Returns
+ :attr:`MonthMixin.month_format` by default.
+
+.. method:: MonthMixin.get_month()
+
+ Returns the month for which this view will display data. Tries the
+ following sources, in order:
+
+ * The value of the :attr:`MonthMixin.month` attribute.
+ * The value of the `month` argument captured in the URL pattern
+ * The value of the `month` GET query argument.
+
+ Raises a 404 if no valid month specification can be found.
+
+.. method:: MonthMixin.get_next_month(date)
+
+ Returns a date object containing the first day of the month after
+ the date provided. Returns `None`` if mixed with a view that sets
+ ``allow_future = False``, and the next month is in the future.
+ If ``allow_empty = False``, returns the next month that contains
+ data.
+
+.. method:: MonthMixin.get_prev_month(date)
+
+ Returns a date object containing the first day of the month before
+ the date provided. If ``allow_empty = False``, returns the previous
+ month that contained data.
+
+DayMixin
+~~~~~~~~~
+.. class:: DayMixin()
+
+A mixin that can be used to retrieve and provide parsing information
+for a day component of a date.
+
+**Attributes**
+
+.. attribute:: DayMixin.day_format
+
+ The strftime_ format to use when parsing the day. By default,
+ this is ``'%d'``.
+
+.. attribute:: DayMixin.day
+
+ **Optional** The value for the day (as a string). By default,
+ set to ``None``, which means the day will be determined using
+ other means.
+
+**Methods**
+
+.. method:: DayMixin.get_day_format()
+
+ Returns the strftime_ format to use when parsing the day. Returns
+ :attr:`DayMixin.day_format` by default.
+
+.. method:: DayMixin.get_day()
+
+ Returns the day for which this view will display data. Tries the
+ following sources, in order:
+
+ * The value of the :attr:`DayMixin.day` attribute.
+ * The value of the `day` argument captured in the URL pattern
+ * The value of the `day` GET query argument.
+
+ Raises a 404 if no valid day specification can be found.
+
+.. method:: MonthMixin.get_next_day(date)
+
+ Returns a date object containing the next day after the date
+ provided. Returns `None`` if mixed with a view that sets
+ ``allow_future = False``, and the next day is in the future. If
+ ``allow_empty = False``, returns the next day that contains
+ data.
+
+.. method:: MonthMixin.get_prev_day(date)
+
+ Returns a date object containing the previous day. If
+ ``allow_empty = False``, returns the previous day that contained
+ data.
+
+WeekMixin
+~~~~~~~~~
+.. class:: WeekMixin()
+
+A mixin that can be used to retrieve and provide parsing information
+for a week component of a date.
+
+**Attributes**
+
+.. attribute:: WeekMixin.week_format
+
+ The strftime_ format to use when parsing the week. By default,
+ this is ``'%U'``.
+
+.. attribute:: WeekMixin.week
+
+ **Optional** The value for the week (as a string). By default,
+ set to ``None``, which means the week will be determined using
+ other means.
+
+**Methods**
+
+.. method:: WeekMixin.get_week_format()
+
+ Returns the strftime_ format to use when parsing the week. Returns
+ :attr:`WeekMixin.week_format` by default.
+
+.. method:: WeekMixin.get_week()
+
+ Returns the week for which this view will display data. Tries the
+ following sources, in order:
+
+ * The value of the :attr:`WeekMixin.week` attribute.
+ * The value of the `week` argument captured in the URL pattern
+ * The value of the `week` GET query argument.
+
+ Raises a 404 if no valid week specification can be found.
+
+
+DateMixin
+~~~~~~~~~
+.. class:: DateMixin()
+
+A mixin class providing common behavior for all date-based views.
+
+**Attributes**
+
+.. attribute:: BaseDateListView.date_field
+
+ The name of the ``DateField`` or ``DateTimeField`` in the
+ ``QuerySet``'s model that the date-based archive should use to
+ determine the objects on the page.
+
+.. attribute:: BaseDateListView.allow_future
+
+ A boolean specifying whether to include "future" objects on this
+ page, where "future" means objects in which the field specified in
+ ``date_field`` is greater than the current date/time. By default,
+ this is ``False``.
+
+**Methods**
+
+.. method:: BaseDateListView.get_date_field()
+
+ Returns the name of the field that contains the date data that
+ this view will operate on. Returns :attr:`DateMixin.date_field` by
+ default.
+
+.. method:: BaseDateListView.get_allow_future()
+
+ Determine whether to include "future" objects on this page, where
+ "future" means objects in which the field specified in
+ ``date_field`` is greater than the current date/time. Returns
+ :attr:`DateMixin.date_field` by default.
+
+BaseDateListView
+~~~~~~~~~~~~~~~~
+.. class:: BaseDateListView()
+
+A base class that provides common behavior for all date-based views.
+There won't normally be a reason to instantiate
+:class:`~django.views.generic.dates.BaseDateListView`; instantiate one of
+the subclasses instead.
+
+While this view (and it's subclasses) are executing,
+``self.object_list`` will contain the list of objects that the view is
+operating upon, and ``self.date_list`` will contain the list of dates
+for which data is available.
+
+**Mixins**
+
+ * :class:`~django.views.generic.dates.DateMixin`
+ * :class:`~django.views.generic.list.MultipleObjectMixin`
+
+**Attributes**
+
+.. attribute:: BaseDateListView.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 instead of displaying an empty page. By
+ default, this is ``True``.
+
+**Methods**
+
+.. method:: ArchiveView.get_dated_items():
+
+ Returns a 3-tuple containing::
+
+ (date_list, latest, extra_context)
+
+ ``date_list`` is the list of dates for which data is available.
+ ``object_list`` is the list of objects ``extra_context`` is a
+ dictionary of context data that will be added to any context data
+ provided by the
+ :class:`~django.db.views.generic.list.MultiplObjectMixin`.
+
+.. method:: BaseDateListView.get_dated_queryset(**lookup)
+
+ Returns a queryset, filtered using the query arguments defined by
+ ``lookup``. Enforces any restrictions on the queryset, such as
+ ``allow_empty`` and ``allow_future``.
+
+.. method:: BaseDateListView.get_date_list(queryset, date_type)
+
+ Returns the list of dates of type ``date_type`` for which
+ ``queryset`` contains entries. For example, ``get_date_list(qs,
+ 'year')`` will return the list of years for which ``qs`` has
+ entries. See :meth:``~django.db.models.QuerySet.dates()` for the
+ ways that the ``date_type`` argument can be used.
+
+
+Generic views
+=============
+
+Simple generic views
+--------------------
+
+.. currentmodule:: django.views.generic.base
+
+View
+~~~~
+.. class:: View()
+
+The master class-based base view. All other generic class-based views
+inherit from this base class.
+
+Each request served by a :class:`~django.views.generic.base.View` has
+an independent state; therefore, it is safe to store state variables
+on the instance (i.e., ``self.foo = 3`` is a thread-safe operation).
+
+A class-based view is deployed into a URL pattern using the
+:meth:`~View.as_view()` classmethod::
+
+ urlpatterns = patterns('',
+ (r'^view/$', MyView.as_view(size=42)),
+ )
+
+Any argument passed into :meth:`~View.as_view()` will be assigned onto
+the instance that is used to service a request. Using the previous
+example, this means that every request on ``MyView`` is able to
+interrogate ``self.size``.
+
+.. admonition:: Thread safety with view arguments
+
+ Arguments passed to a view are shared between every instance of a
+ view. This means that you shoudn't use a list, dictionary, or any
+ other variable object as an argument to a view. If you did, the
+ actions of one user visiting your view could have an effect on
+ subsequent users visiting the same view.
+
+**Methods**
+
+.. method:: View.dispatch(request, *args, **kwargs)
+
+ The ``view`` part of the view -- the method that accepts a
+ ``request`` argument plus arguments, and returns a HTTP response.
+
+ The default implementation will inspect the HTTP method and
+ attempt to delegate to a method that matches the HTTP method; a
+ ``GET`` will be delegated to :meth:`~View.get()`, a ``POST`` to
+ :meth:`~View.post()`, and so on.
+
+ The default implementation also sets ``request``, ``args`` and
+ ``kwargs`` as instance variables, so any method on the view can
+ know the full details of the request that was made to invoke the
+ view.
+
+.. method:: View.http_method_not_allowed(request, *args, **kwargs)
+
+ If the view was called with HTTP method it doesn't support, this
+ method is called instead.
+
+ The default implementation returns ``HttpResponseNotAllowed``
+ with list of allowed methods in plain text.
+
+TemplateView
+~~~~~~~~~~~~
+.. class:: TemplateView()
+
+Renders a given template, passing it a ``{{ params }}`` template
+variable, which is a dictionary of the parameters captured in the URL.
+
+**Mixins**
+
+ * :class:`django.views.generic.base.TemplateResponseMixin`
+
+**Attributes**
+
+.. attribute:: TemplateView.template_name
+
+ The full name of a template to use.
+
+**Methods**
+
+.. method:: TemplateView.get_context_data(**kwargs)
+
+ Return a context data dictionary consisting of the contents of
+ ``kwargs`` stored in the context variable ``params``.
+
+**Context**
+
+ * ``params``: The dictionary of keyword arguments captured from
+ the URL pattern that served the view.
+
+RedirectView
+~~~~~~~~~~~~
+.. class:: 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).
+
+**Mixins**
+
+None.
+
+**Attributes**
+
+.. attribute:: RedirectView.url
+
+ The URL to redirect to, as a string. Or ``None`` to raise a 410
+ (Gone) HTTP error.
+
+.. attribute:: RedirectView.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``.
+
+.. attribute:: RedirectView.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**
+
+.. method:: RedirectView.get_redirect_url(**kwargs)
+
+ Constructs the target URL for redirection.
+
+ The default implementation uses :attr:`~RedirectView.url` as a
+ starting string, performs expansion of ``%`` parameters in that
+ string, as well as the appending of query string if requested by
+ :attr:`~RedirectView.query_string`. Subclasses may implement any
+ behavior they wish, as long as the method returns a redirect-ready
+ URL string.
+
+Detail views
+------------
+
+.. currentmodule:: django.views.generic.detail
+
+DetailView
+~~~~~~~~~~
+.. class:: BaseDetailView()
+.. class:: DetailView()
+
+A page representing an individual object.
+
+While this view is executing, ``self.object`` will contain the object that
+the view is operating upon.
+
+:class:`~django.views.generic.base.BaseDetailView` implements the same
+behavior as :class:`~django.views.generic.base.DetailView`, but doesn't