Kaydet (Commit) 0fcb0945 authored tarafından Russell Keith-Magee's avatar Russell Keith-Magee

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
üst fa2159f8
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
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,6 +8,12 @@ from django.contrib.auth.views import redirect_to_login
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,6 +7,13 @@ from django.core.xheaders import populate_xheaders
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,
......
This diff is collapsed.
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()`.
"""
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'
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.
"""
......@@ -4,6 +4,13 @@ from django.core.xheaders import populate_xheaders
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',
......
......@@ -2,6 +2,12 @@ from django.template import loader, RequestContext
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')
......
......@@ -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
==============================
......
......@@ -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
......
......@@ -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,)))
......
This diff is collapsed.
......@@ -8,7 +8,7 @@ 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/http/generic-views>`.
</topics/generic-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
......
......@@ -12,7 +12,7 @@ API Reference
exceptions
files/index
forms/index
generic-views
class-based-views
middleware
models/index
request-response
......@@ -22,3 +22,11 @@ API Reference
unicode
utils
validators
Deprecated features
-------------------
.. toctree::
:maxdepth: 1
generic-views
......@@ -17,6 +17,23 @@ upgrade path from Django 1.2.
What's new in Django 1.3
========================
Class-based views
~~~~~~~~~~~~~~~~~
Django 1.3 adds a framework that allows you to use a class as a view.
This means you can compose a view out of a collection of methods that
can be subclassed and overridden to provide
Analogs of all the old function-based generic views have been
provided, along with a completely generic view base class that can be
used as the basis for reusable applications that can be easily
extended.
See :doc:`the documentation on Generic Views</topics/generic-views>`
for more details. There is also a document to help you :doc:`convert
your function-based generic views to class-based
views</topics/generic-views-migration>`.
Logging
~~~~~~~
......@@ -174,6 +191,18 @@ If you are currently using the ``mod_python`` request handler, it is strongly
encouraged you redeploy your Django instances using :doc:`mod_wsgi
</howto/deployment/modwsgi>`.
Function-based generic views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As a result of the introduction of class-based generic views, the
function-based generic views provided by Django have been deprecated.
The following modules and the views they contain have been deprecated:
* :mod:`django.views.generic.create_update`
* :mod:`django.views.generic.date_based`
* :mod:`django.views.generic.list_detail`
* :mod:`django.views.generic.simple`
Test client response ``template`` attribute
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
......
This diff is collapsed.
======================================
Migrating function-based generic views
======================================
All the :doc:`function-based generic views</ref/generic-views>`
that existed in Django 1.2 have analogs as :doc:`class-based generic
views</ref/class-based-views>` in Django 1.3. The feature set
exposed in those function-based views can be replicated in a
class-based way.
How to migrate
==============
Replace generic views with generic classes
------------------------------------------
Existing usage of function-based generic views should be replaced with
their class-based analogs:
==================================================== ====================================================
Old function-based generic view New class-based generic view
==================================================== ====================================================
``django.views.generic.simple.direct_to_template`` :class:`django.views.generic.base.TemplateView`
``django.views.generic.simple.redirect_to`` :class:`django.views.generic.base.RedirectView`
``django.views.generic.list_detail.object_list`` :class:`django.views.generic.list.ListView`
``django.views.generic.list_detail.object_detail`` :class:`django.views.generic.detail.DetailView`
``django.views.generic.create_update.create_object`` :class:`django.views.generic.edit.CreateView`
``django.views.generic.create_update.update_object`` :class:`django.views.generic.edit.UpdateView`
``django.views.generic.create_update.delete_object`` :class:`django.views.generic.edit.DeleteView`
``django.views.generic.date_based.archive_index`` :class:`django.views.generic.dates.ArchiveIndexView`
``django.views.generic.date_based.archive_year`` :class:`django.views.generic.dates.YearArchiveView`
``django.views.generic.date_based.archive_month`` :class:`django.views.generic.dates.MonthArchiveView`
``django.views.generic.date_based.archive_week`` :class:`django.views.generic.dates.WeekArchiveView`
``django.views.generic.date_based.archive_day`` :class:`django.views.generic.dates.DayArchiveView`
``django.views.generic.date_based.archive_today`` :class:`django.views.generic.dates.TodayArchiveView`
``django.views.generic.date_based.object_detail`` :class:`django.views.generic.dates.DateDetailView`
==================================================== ====================================================
To do this, replace the reference to the generic view function with
a ``as_view()`` instantiation of the class-based view. For example,
the old-style ``direct_to_template`` pattern::
('^about/$', direct_to_template, {'template': 'about.html'})
can be replaced with an instance of
:class:`~django.views.generic.base.TemplateView`::
('^about/$', TemplateView.as_view(template_name='about.html'))
``template`` argument to ``direct_to_template`` views
-----------------------------------------------------
The ``template`` argument to the ``direct_to_template`` view has been renamed
``template_name``. This has ben done to maintain consistency with other views.
``object_id`` argument to detail views
--------------------------------------
The object_id argument to the ``object_detail`` view has been renamed
``pk`` on the :class:`~django.views.generic.detail.DetailView`.
``template_object_name``
------------------------
``template_object_name`` has been renamed ``context_object_name``,
reflecting the fact that the context data can be used for purposes
other than template rendering (e.g., to populate JSON output).
The ``_list`` suffix on list views
----------------------------------
In a function-based :class:`ListView`, the ``template_object_name``
was appended with the suffix ``'_list'`` to yield the final context
variable name. In a class-based ``ListView``, the
``context_object_name`` is used verbatim.
``extra_context``
-----------------
Function-based generic views provided an ``extra_context`` argument
as way to insert extra items into the context at time of rendering.
Class-based views don't provide an ``extra_context`` argument.
Instead, you subclass the view, overriding :meth:`get_context_data()`.
For example::
class MyListView(ListView):
def get_context_data(self, **kwargs):
context = super(MyListView, self).get_context_data(**kwargs)
context.update({
'foo': 42,
'bar': 37
})
return context
``mimetype``
------------
Some function-based generic views provided a ``mimetype`` argument
as way to control the mimetype of the response.
Class-based views don't provide a ``mimetype`` argument. Instead, you
subclass the view, overriding
:meth:`TemplateResponseMixin.get_response()` and pass in arguments for
the HttpResponse constructor. For example::
class MyListView(ListView):
def get_response(self, content, **kwargs):
return super(MyListView, self).get_response(content,
content_type='application/json', **kwargs)
``context_processors``
----------------------
Some function-based generic views provided a ``context_processors``
argument that could be used to force the use of specialized context
processors when rendering template content.
Class-based views don't provide a ``context_processors`` argument.
Instead, you subclass the view, overriding
:meth:`TemplateResponseMixin.get_context_instance()`. For example::
class MyListView(ListView):
def get_context_instance(self, context):
return RequestContext(self.request,
context,
processors=[custom_processor])
......@@ -12,7 +12,8 @@ Introductions to all the key parts of Django you'll need to know:
forms/index
forms/modelforms
templates
generic-views
class-based-views
generic-views-migration
files
testing
auth
......@@ -26,3 +27,10 @@ Introductions to all the key parts of Django you'll need to know:
settings
signals
Deprecated features
-------------------
.. toctree::
:maxdepth: 1
generic-views
import unittest
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.test import TestCase, RequestFactory
from django.utils import simplejson
from django.views.generic import View, TemplateView, RedirectView
class SimpleView(View):
"""
A simple view with a docstring.
"""
def get(self, request):
return HttpResponse('This is a simple view')
class SimplePostView(SimpleView):
post = SimpleView.get
class CustomizableView(SimpleView):
parameter = {}
def decorator(view):
view.is_decorated = True
return view
class DecoratedDispatchView(SimpleView):
@decorator
def dispatch(self, request, *args, **kwargs):
return super(DecoratedDispatchView, self).dispatch(request, *args, **kwargs)
class AboutTemplateView(TemplateView):
def get(self, request):
return self.render_to_response({})
def get_template_names(self):
return ['generic_views/about.html']
class AboutTemplateAttributeView(TemplateView):
template_name = 'generic_views/about.html'
def get(self, request):
return self.render_to_response(context={})
class InstanceView(View):
def get(self, request):
return self
class ViewTest(unittest.TestCase):
rf = RequestFactory()
def _assert_simple(self, response):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'This is a simple view')
def test_no_init_kwargs(self):
"""
Test that a view can't be accidentally instantiated before deployment
"""
try:
view = SimpleView(key='value').as_view()
self.fail('Should not be able to instantiate a view')
except AttributeError:
pass
def test_no_init_args(self):
"""
Test that a view can't be accidentally instantiated before deployment
"""
try:
view = SimpleView.as_view('value')
self.fail('Should not be able to use non-keyword arguments instantiating a view')
except TypeError:
pass
def test_pathological_http_method(self):
"""
The edge case of a http request that spoofs an existing method name is caught.
"""
self.assertEqual(SimpleView.as_view()(
self.rf.get('/', REQUEST_METHOD='DISPATCH')
).status_code, 405)
def test_get_only(self):
"""
Test a view which only allows GET doesn't allow other methods.
"""
self._assert_simple(SimpleView.as_view()(self.rf.get('/')))
self.assertEqual(SimpleView.as_view()(self.rf.post('/')).status_code, 405)
self.assertEqual(SimpleView.as_view()(
self.rf.get('/', REQUEST_METHOD='FAKE')
).status_code, 405)
def test_get_and_post(self):
"""
Test a view which only allows both GET and POST.
"""
self._assert_simple(SimplePostView.as_view()(self.rf.get('/')))
self._assert_simple(SimplePostView.as_view()(self.rf.post('/')))
self.assertEqual(SimplePostView.as_view()(
self.rf.get('/', REQUEST_METHOD='FAKE')
).status_code, 405)
def test_invalid_keyword_argument(self):
"""
Test that view arguments must be predefined on the class and can't
be named like a HTTP method.
"""
# Check each of the allowed method names
for method in SimpleView.http_method_names:
kwargs = dict(((method, "value"),))
self.assertRaises(TypeError, SimpleView.as_view, **kwargs)
# Check the case view argument is ok if predefined on the class...
CustomizableView.as_view(parameter="value")
# ...but raises errors otherwise.
self.assertRaises(TypeError, CustomizableView.as_view, foobar="value")
def test_calling_more_than_once(self):
"""
Test a view can only be called once.
"""
request = self.rf.get('/')
view = InstanceView.as_view()
self.assertNotEqual(view(request), view(request))
def test_class_attributes(self):
"""
Test that the callable returned from as_view() has proper
docstring, name and module.
"""
self.assertEqual(SimpleView.__doc__, SimpleView.as_view().__doc__)
self.assertEqual(SimpleView.__name__, SimpleView.as_view().__name__)
self.assertEqual(SimpleView.__module__, SimpleView.as_view().__module__)
def test_dispatch_decoration(self):
"""
Test that attributes set by decorators on the dispatch method
are also present on the closure.
"""
self.assertTrue(DecoratedDispatchView.as_view().is_decorated)
class TemplateViewTest(TestCase):
urls = 'regressiontests.generic_views.urls'
rf = RequestFactory()
def _assert_about(self, response):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, '<h1>About</h1>')
def test_get(self):
"""
Test a view that simply renders a template on GET
"""
self._assert_about(AboutTemplateView.as_view()(self.rf.get('/about/')))
def test_get_template_attribute(self):
"""
Test a view that renders a template on GET with the template name as
an attribute on the class.
"""
self._assert_about(AboutTemplateAttributeView.as_view()(self.rf.get('/about/')))
def test_get_generic_template(self):
"""
Test a completely generic view that renders a template on GET
with the template name as an argument at instantiation.
"""
self._assert_about(TemplateView.as_view(template_name='generic_views/about.html')(self.rf.get('/about/')))
def test_template_params(self):
"""
A generic template view passes kwargs as context.
"""
response = self.client.get('/template/simple/bar/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['params'], {'foo': 'bar'})
def test_extra_template_params(self):
"""
A template view can be customized to return extra context.
"""
response = self.client.get('/template/custom/bar/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['params'], {'foo': 'bar'})
self.assertEqual(response.context['key'], 'value')
class RedirectViewTest(unittest.TestCase):
rf = RequestFactory()
def test_no_url(self):
"Without any configuration, returns HTTP 410 GONE"
response = RedirectView.as_view()(self.rf.get('/foo/'))
self.assertEquals(response.status_code, 410)
def test_permanaent_redirect(self):
"Default is a permanent redirect"
response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/'))
self.assertEquals(response.status_code, 301)
self.assertEquals(response['Location'], '/bar/')
def test_temporary_redirect(self):
"Permanent redirects are an option"
response = RedirectView.as_view(url='/bar/', permanent=False)(self.rf.get('/foo/'))
self.assertEquals(response.status_code, 302)
self.assertEquals(response['Location'], '/bar/')
def test_include_args(self):
"GET arguments can be included in the redirected URL"
response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/'))
self.assertEquals(response.status_code, 301)
self.assertEquals(response['Location'], '/bar/')
response = RedirectView.as_view(url='/bar/', query_string=True)(self.rf.get('/foo/?pork=spam'))
self.assertEquals(response.status_code, 301)
self.assertEquals(response['Location'], '/bar/?pork=spam')
def test_parameter_substitution(self):
"Redirection URLs can be parameterized"
response = RedirectView.as_view(url='/bar/%(object_id)d/')(self.rf.get('/foo/42/'), object_id=42)
self.assertEquals(response.status_code, 301)
self.assertEquals(response['Location'], '/bar/42/')
This diff is collapsed.
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from regressiontests.generic_views.models import Author, Page
class DetailViewTest(TestCase):
fixtures = ['generic-views-test-data.json']
urls = 'regressiontests.generic_views.urls'
def test_simple_object(self):
res = self.client.get('/detail/obj/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], {'foo': 'bar'})
self.assertTemplateUsed(res, 'generic_views/detail.html')
def test_detail_by_pk(self):
res = self.client.get('/detail/author/1/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['author'], Author.objects.get(pk=1))
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_detail_by_slug(self):
res = self.client.get('/detail/author/byslug/scott-rosenberg/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(slug='scott-rosenberg'))
self.assertEqual(res.context['author'], Author.objects.get(slug='scott-rosenberg'))
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_template_name(self):
res = self.client.get('/detail/author/1/template_name/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['author'], Author.objects.get(pk=1))
self.assertTemplateUsed(res, 'generic_views/about.html')
def test_template_name_suffix(self):
res = self.client.get('/detail/author/1/template_name_suffix/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['author'], Author.objects.get(pk=1))
self.assertTemplateUsed(res, 'generic_views/author_view.html')
def test_template_name_field(self):
res = self.client.get('/detail/page/1/field/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Page.objects.get(pk=1))
self.assertEqual(res.context['page'], Page.objects.get(pk=1))
self.assertTemplateUsed(res, 'generic_views/page_template.html')
def test_context_object_name(self):
res = self.client.get('/detail/author/1/context_object_name/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=1))
self.assertFalse('author' in res.context)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_duplicated_context_object_name(self):
res = self.client.get('/detail/author/1/dupe_context_object_name/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertFalse('author' in res.context)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_invalid_url(self):
self.assertRaises(AttributeError, self.client.get, '/detail/author/invalid/url/')
def test_invalid_queryset(self):
self.assertRaises(ImproperlyConfigured, self.client.get, '/detail/author/invalid/qs/')
This diff is collapsed.
[
{
"model": "generic_views.author",
"pk": 1,
"fields": {
"name": "Roberto Bolaño",
"slug": "roberto-bolano"
}
},
{
"model": "generic_views.author",
"pk": 2,
"fields": {
"name": "Scott Rosenberg",
"slug": "scott-rosenberg"
}
},
{
"model": "generic_views.book",
"pk": 1,
"fields": {
"name": "2066",
"slug": "2066",
"pages": "800",
"authors": [1],
"pubdate": "2008-10-01"
}
},
{
"model": "generic_views.book",
"pk": 2,
"fields": {
"name": "Dreaming in Code",
"slug": "dreaming-in-code",
"pages": "300",
"pubdate": "2006-05-01"
}
},
{
"model": "generic_views.page",
"pk": 1,
"fields": {
"template": "generic_views/page_template.html",
"content": "I was once bitten by a moose."
}
}
]
\ No newline at end of file
from django import forms
from regressiontests.generic_views.models import Author
class AuthorForm(forms.ModelForm):
name = forms.CharField()
slug = forms.SlugField()
class Meta:
model = Author
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from regressiontests.generic_views.models import Author
class ListViewTests(TestCase):
fixtures = ['generic-views-test-data.json']
urls = 'regressiontests.generic_views.urls'
def test_items(self):
res = self.client.get('/list/dict/')
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/list.html')
self.assertEqual(res.context['object_list'][0]['first'], 'John')
def test_queryset(self):
res = self.client.get('/list/authors/')
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
self.assertEqual(list(res.context['object_list']), list(Author.objects.all()))
self.assertEqual(list(res.context['authors']), list(Author.objects.all()))
self.assertEqual(res.context['paginator'], None)
self.assertEqual(res.context['page_obj'], None)
self.assertEqual(res.context['is_paginated'], False)
def test_paginated_queryset(self):
self._make_authors(100)
res = self.client.get('/list/authors/paginated/')
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
self.assertEqual(len(res.context['authors']), 30)
self.assertEqual(res.context['is_paginated'], True)
self.assertEqual(res.context['page_obj'].number, 1)
self.assertEqual(res.context['paginator'].num_pages, 4)
self.assertEqual(res.context['authors'][0].name, 'Author 00')
self.assertEqual(list(res.context['authors'])[-1].name, 'Author 29')
def test_paginated_queryset_shortdata(self):
res = self.client.get('/list/authors/paginated/')
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
self.assertEqual(list(res.context['object_list']), list(Author.objects.all()))
self.assertEqual(list(res.context['authors']), list(Author.objects.all()))
self.assertEqual(res.context['paginator'], None)
self.assertEqual(res.context['page_obj'], None)
self.assertEqual(res.context['is_paginated'], False)
def test_paginated_get_page_by_query_string(self):
self._make_authors(100)
res = self.client.get('/list/authors/paginated/', {'page': '2'})
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
self.assertEqual(len(res.context['authors']), 30)
self.assertEqual(res.context['authors'][0].name, 'Author 30')
self.assertEqual(res.context['page_obj'].number, 2)
def test_paginated_get_last_page_by_query_string(self):
self._make_authors(100)
res = self.client.get('/list/authors/paginated/', {'page': 'last'})
self.assertEqual(res.status_code, 200)
self.assertEqual(len(res.context['authors']), 10)
self.assertEqual(res.context['authors'][0].name, 'Author 90')
self.assertEqual(res.context['page_obj'].number, 4)
def test_paginated_get_page_by_urlvar(self):
self._make_authors(100)
res = self.client.get('/list/authors/paginated/3/')
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
self.assertEqual(len(res.context['authors']), 30)
self.assertEqual(res.context['authors'][0].name, 'Author 60')
self.assertEqual(res.context['page_obj'].number, 3)
def test_paginated_page_out_of_range(self):
self._make_authors(100)
res = self.client.get('/list/authors/paginated/42/')
self.assertEqual(res.status_code, 404)
def test_paginated_invalid_page(self):
self._make_authors(100)
res = self.client.get('/list/authors/paginated/?page=frog')
self.assertEqual(res.status_code, 404)
def test_allow_empty_false(self):
res = self.client.get('/list/authors/notempty/')
self.assertEqual(res.status_code, 200)
Author.objects.all().delete()
res = self.client.get('/list/authors/notempty/')
self.assertEqual(res.status_code, 404)
def test_template_name(self):
res = self.client.get('/list/authors/template_name/')
self.assertEqual(res.status_code, 200)
self.assertEqual(list(res.context['object_list']), list(Author.objects.all()))
self.assertEqual(list(res.context['authors']), list(Author.objects.all()))
self.assertTemplateUsed(res, 'generic_views/list.html')
def test_template_name_suffix(self):
res = self.client.get('/list/authors/template_name_suffix/')
self.assertEqual(res.status_code, 200)
self.assertEqual(list(res.context['object_list']), list(Author.objects.all()))
self.assertEqual(list(res.context['authors']), list(Author.objects.all()))
self.assertTemplateUsed(res, 'generic_views/author_objects.html')
def test_context_object_name(self):
res = self.client.get('/list/authors/context_object_name/')
self.assertEqual(res.status_code, 200)
self.assertEqual(list(res.context['object_list']), list(Author.objects.all()))
self.assertEqual(list(res.context['author_list']), list(Author.objects.all()))
self.assertFalse('authors' in res.context)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
def test_duplicate_context_object_name(self):
res = self.client.get('/list/authors/dupe_context_object_name/')
self.assertEqual(res.status_code, 200)
self.assertEqual(list(res.context['object_list']), list(Author.objects.all()))
self.assertFalse('author_list' in res.context)
self.assertFalse('authors' in res.context)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
def test_missing_items(self):
self.assertRaises(ImproperlyConfigured, self.client.get, '/list/authors/invalid/')
def _make_authors(self, n):
Author.objects.all().delete()
for i in range(n):
Author.objects.create(name='Author %02i' % i, slug='a%s' % i)
from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('artist_detail', (), {'pk': self.id})
class Author(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField()
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=300)
slug = models.SlugField()
pages = models.IntegerField()
authors = models.ManyToManyField(Author)
pubdate = models.DateField()
class Meta:
ordering = ['-pubdate']
def __unicode__(self):
return self.name
class Page(models.Model):
content = models.TextField()
template = models.CharField(max_length=300)
This is a {% if tasty %}tasty {% endif %}{{ apple.color }} apple{{ extra }}
\ No newline at end of file
{% for item in object_list %}
{{ item }}
{% endfor %}
\ No newline at end of file
{% for item in object_list %}
{{ item }}
{% endfor %}
\ No newline at end of file
This is an alternate template_name_suffix for an {{ author }}.
\ No newline at end of file
Archive of books from {{ date_list }}.
\ No newline at end of file
Archive for {{ day }}. Previous day is {{ previous_day }}
\ No newline at end of file
{% for item in object_list %}
{{ item }}
{% endfor %}
\ No newline at end of file
{% for item in object_list %}
{{ item }}
{% endfor %}
\ No newline at end of file
This is some content: {{ content }}
\ No newline at end of file
from regressiontests.generic_views.base import ViewTest, TemplateViewTest, RedirectViewTest
from regressiontests.generic_views.dates import ArchiveIndexViewTests, YearArchiveViewTests, MonthArchiveViewTests, WeekArchiveViewTests, DayArchiveViewTests, DateDetailViewTests
from regressiontests.generic_views.detail import DetailViewTest
from regressiontests.generic_views.edit import CreateViewTests, UpdateViewTests, DeleteViewTests
from regressiontests.generic_views.list import ListViewTests
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment