PageRenderTime 6ms CodeModel.GetById 16ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/topics/class-based-views.txt

https://code.google.com/p/mango-py/
Plain Text | 619 lines | 464 code | 155 blank | 0 comment | 0 complexity | 1fd5109e062796e68e1e9e6c434de666 MD5 | raw file
  1=========================
  2Class-based generic views
  3=========================
  4
  5.. versionadded:: 1.3
  6
  7.. note::
  8    Prior to Django 1.3, generic views were implemented as functions. The
  9    function-based implementation has been deprecated in favor of the
 10    class-based approach described here.
 11
 12    For details on the previous generic views implementation,
 13    see the :doc:`topic guide </topics/generic-views>` and
 14    :doc:`detailed reference </ref/generic-views>`.
 15
 16Writing Web applications can be monotonous, because we repeat certain patterns
 17again and again. Django tries to take away some of that monotony at the model
 18and template layers, but Web developers also experience this boredom at the view
 19level.
 20
 21Django's *generic views* were developed to ease that pain. They take certain
 22common idioms and patterns found in view development and abstract them so that
 23you can quickly write common views of data without having to write too much
 24code.
 25
 26We can recognize certain common tasks, like displaying a list of objects, and
 27write code that displays a list of *any* object. Then the model in question can
 28be passed as an extra argument to the URLconf.
 29
 30Django ships with generic views to do the following:
 31
 32    * Perform common "simple" tasks: redirect to a different page and
 33      render a given template.
 34
 35    * Display list and detail pages for a single object. If we were creating an
 36      application to manage conferences then a ``TalkListView`` and a
 37      ``RegisteredUserListView`` would be examples of list views. A single
 38      talk page is an example of what we call a "detail" view.
 39
 40    * Present date-based objects in year/month/day archive pages,
 41      associated detail, and "latest" pages.
 42      `The Django Weblog <http://www.djangoproject.com/weblog/>`_'s
 43      year, month, and day archives are built with these, as would be a typical
 44      newspaper's archives.
 45
 46    * Allow users to create, update, and delete objects -- with or
 47      without authorization.
 48
 49Taken together, these views provide easy interfaces to perform the most common
 50tasks developers encounter.
 51
 52
 53Simple usage
 54============
 55
 56Class-based generic views (and any class-based views that inherit from
 57the base classes Django provides) can be configured in two
 58ways: subclassing, or passing in arguments directly in the URLconf.
 59
 60When you subclass a class-based view, you can override attributes
 61(such as the ``template_name``) or methods (such as ``get_context_data``)
 62in your subclass to provide new values or methods. Consider, for example,
 63a view that just displays one template, ``about.html``. Django has a
 64generic view to do this - :class:`~django.views.generic.base.TemplateView` -
 65so we can just subclass it, and override the template name::
 66
 67    # some_app/views.py
 68    from django.views.generic import TemplateView
 69
 70    class AboutView(TemplateView):
 71        template_name = "about.html"
 72
 73Then, we just need to add this new view into our URLconf. As the class-based
 74views themselves are classes, we point the URL to the ``as_view`` class method
 75instead, which is the entry point for class-based views::
 76
 77    # urls.py
 78    from django.conf.urls.defaults import *
 79    from some_app.views import AboutView
 80
 81    urlpatterns = patterns('',
 82        (r'^about/', AboutView.as_view()),
 83    )
 84
 85Alternatively, if you're only changing a few simple attributes on a
 86class-based view, you can simply pass the new attributes into the ``as_view``
 87method call itself::
 88
 89    from django.conf.urls.defaults import *
 90    from django.views.generic import TemplateView
 91
 92    urlpatterns = patterns('',
 93        (r'^about/', TemplateView.as_view(template_name="about.html")),
 94    )
 95
 96A similar overriding pattern can be used for the ``url`` attribute on
 97:class:`~django.views.generic.base.RedirectView`, another simple
 98generic view.
 99
100
101Generic views of objects
102========================
103
104:class:`~django.views.generic.base.TemplateView` certainly is useful,
105but Django's generic views really shine when it comes to presenting
106views of your database content. Because it's such a common task,
107Django comes with a handful of built-in generic views that make
108generating list and detail views of objects incredibly easy.
109
110Let's take a look at one of these generic views: the "object list" view. We'll
111be using these models::
112
113    # models.py
114    from django.db import models
115
116    class Publisher(models.Model):
117        name = models.CharField(max_length=30)
118        address = models.CharField(max_length=50)
119        city = models.CharField(max_length=60)
120        state_province = models.CharField(max_length=30)
121        country = models.CharField(max_length=50)
122        website = models.URLField()
123
124        class Meta:
125            ordering = ["-name"]
126
127        def __unicode__(self):
128            return self.name
129
130    class Book(models.Model):
131        title = models.CharField(max_length=100)
132        authors = models.ManyToManyField('Author')
133        publisher = models.ForeignKey(Publisher)
134        publication_date = models.DateField()
135
136To build a list page of all publishers, we'd use a URLconf along these lines::
137
138    from django.conf.urls.defaults import *
139    from django.views.generic import ListView
140    from books.models import Publisher
141
142    urlpatterns = patterns('',
143        (r'^publishers/$', ListView.as_view(
144            model=Publisher,
145        )),
146    )
147
148That's all the Python code we need to write. We still need to write a template,
149however. We could explicitly tell the view which template to use
150by including a ``template_name`` key in the arguments to as_view, but in
151the absence of an explicit template Django will infer one from the object's
152name. In this case, the inferred template will be
153``"books/publisher_list.html"`` -- the "books" part comes from the name of the
154app that defines the model, while the "publisher" bit is just the lowercased
155version of the model's name.
156
157.. note::
158    Thus, when (for example) the :class:`django.template.loaders.app_directories.Loader`
159    template loader is enabled in :setting:`TEMPLATE_LOADERS`, the template
160    location would be::
161
162        /path/to/project/books/templates/books/publisher_list.html
163
164.. highlightlang:: html+django
165
166This template will be rendered against a context containing a variable called
167``object_list`` that contains all the publisher objects. A very simple template
168might look like the following::
169
170    {% extends "base.html" %}
171
172    {% block content %}
173        <h2>Publishers</h2>
174        <ul>
175            {% for publisher in object_list %}
176                <li>{{ publisher.name }}</li>
177            {% endfor %}
178        </ul>
179    {% endblock %}
180
181That's really all there is to it. All the cool features of generic views come
182from changing the "info" dictionary passed to the generic view. The
183:doc:`generic views reference</ref/class-based-views>` documents all the generic
184views and their options in detail; the rest of this document will consider
185some of the common ways you might customize and extend generic views.
186
187
188Extending generic views
189=======================
190
191.. highlightlang:: python
192
193There's no question that using generic views can speed up development
194substantially. In most projects, however, there comes a moment when the
195generic views no longer suffice. Indeed, the most common question asked by new
196Django developers is how to make generic views handle a wider array of
197situations.
198
199This is one of the reasons generic views were redesigned for the 1.3 release -
200previously, they were just view functions with a bewildering array of options;
201now, rather than passing in a large amount of configuration in the URLconf,
202the recommended way to extend generic views is to subclass them, and override
203their attributes or methods.
204
205
206Making "friendly" template contexts
207-----------------------------------
208
209You might have noticed that our sample publisher list template stores
210all the publishers in a variable named ``object_list``. While this
211works just fine, it isn't all that "friendly" to template authors:
212they have to "just know" that they're dealing with publishers here.
213
214Well, if you're dealing with a model object, this is already done for
215you. When you are dealing with an object or queryset, Django is able
216to populate the context using the verbose name (or the plural verbose
217name, in the case of a list of objects) of the object being displayed.
218This is provided in addition to the default ``object_list`` entry, but
219contains exactly the same data.
220
221If the verbose name (or plural verbose name) still isn't a good match,
222you can manually set the name of the context variable. The
223``context_object_name`` attribute on a generic view specifies the
224context variable to use. In this example, we'll override it in the
225URLconf, since it's a simple change:
226
227.. parsed-literal::
228
229    urlpatterns = patterns('',
230        (r'^publishers/$', ListView.as_view(
231            model=Publisher,
232            **context_object_name="publisher_list",**
233        )),
234    )
235
236Providing a useful ``context_object_name`` is always a good idea. Your
237coworkers who design templates will thank you.
238
239
240Adding extra context
241--------------------
242
243Often you simply need to present some extra information beyond that
244provided by the generic view. For example, think of showing a list of
245all the books on each publisher detail page. The
246:class:`~django.views.generic.detail.DetailView` generic view provides
247the publisher to the context, but it seems there's no way to get
248additional information in that template.
249
250However, there is; you can subclass
251:class:`~django.views.generic.detail.DetailView` and provide your own
252implementation of the ``get_context_data`` method. The default
253implementation of this that comes with
254:class:`~django.views.generic.detail.DetailView` simply adds in the
255object being displayed to the template, but you can override it to show
256more::
257
258    from django.views.generic import DetailView
259    from books.models import Publisher, Book
260
261    class PublisherDetailView(DetailView):
262
263        context_object_name = "publisher"
264        model = Publisher
265
266        def get_context_data(self, **kwargs):
267            # Call the base implementation first to get a context
268            context = super(PublisherDetailView, self).get_context_data(**kwargs)
269            # Add in a QuerySet of all the books
270            context['book_list'] = Book.objects.all()
271            return context
272
273
274Viewing subsets of objects
275--------------------------
276
277Now let's take a closer look at the ``model`` argument we've been
278using all along. The ``model`` argument, which specifies the database
279model that the view will operate upon, is available on all the
280generic views that operate on a single object or a collection of
281objects. However, the ``model`` argument is not the only way to
282specify the objects that the view will operate upon -- you can also
283specify the list of objects using the ``queryset`` argument::
284
285    from django.views.generic import DetailView
286    from books.models import Publisher, Book
287
288    class PublisherDetailView(DetailView):
289
290        context_object_name = "publisher"
291        queryset = Publisher.objects.all()
292
293Specifying ``model = Publisher`` is really just shorthand for saying
294``queryset = Publisher.objects.all()``. However, by using ``queryset``
295to define a filtered list of objects you can be more specific about the
296objects that will be visible in the view (see :doc:`/topics/db/queries`
297for more information about :class:`QuerySet` objects, and see the
298:doc:`class-based views reference </ref/class-based-views>` for the complete
299details).
300
301To pick a simple example, we might want to order a list of books by
302publication date, with the most recent first::
303
304    urlpatterns = patterns('',
305        (r'^publishers/$', ListView.as_view(
306            queryset=Publisher.objects.all(),
307            context_object_name="publisher_list",
308        )),
309        (r'^books/$', ListView.as_view(
310            queryset=Book.objects.order_by("-publication_date"),
311            context_object_name="book_list",
312        )),
313    )
314
315
316That's a pretty simple example, but it illustrates the idea nicely. Of course,
317you'll usually want to do more than just reorder objects. If you want to
318present a list of books by a particular publisher, you can use the same
319technique (here, illustrated using subclassing rather than by passing arguments
320in the URLconf)::
321
322    from django.views.generic import ListView
323    from books.models import Book
324
325    class AcmeBookListView(ListView):
326
327        context_object_name = "book_list"
328        queryset = Book.objects.filter(publisher__name="Acme Publishing")
329        template_name = "books/acme_list.html"
330
331Notice that along with a filtered ``queryset``, we're also using a custom
332template name. If we didn't, the generic view would use the same template as the
333"vanilla" object list, which might not be what we want.
334
335Also notice that this isn't a very elegant way of doing publisher-specific
336books. If we want to add another publisher page, we'd need another handful of
337lines in the URLconf, and more than a few publishers would get unreasonable.
338We'll deal with this problem in the next section.
339
340.. note::
341
342    If you get a 404 when requesting ``/books/acme/``, check to ensure you
343    actually have a Publisher with the name 'ACME Publishing'.  Generic
344    views have an ``allow_empty`` parameter for this case.  See the
345    :doc:`class-based-views reference</ref/class-based-views>` for more details.
346
347
348Dynamic filtering
349-----------------
350
351Another common need is to filter down the objects given in a list page by some
352key in the URL. Earlier we hard-coded the publisher's name in the URLconf, but
353what if we wanted to write a view that displayed all the books by some arbitrary
354publisher?
355
356Handily, the ``ListView`` has a
357:meth:`~django.views.generic.detail.ListView.get_queryset` method we can
358override. Previously, it has just been returning the value of the ``queryset``
359attribute, but now we can add more logic.
360
361The key part to making this work is that when class-based views are called,
362various useful things are stored on ``self``; as well as the request
363(``self.request``) this includes the positional (``self.args``) and name-based
364(``self.kwargs``) arguments captured according to the URLconf.
365
366Here, we have a URLconf with a single captured group::
367
368    from books.views import PublisherBookListView
369
370    urlpatterns = patterns('',
371        (r'^books/(\w+)/$', PublisherBookListView.as_view()),
372    )
373
374Next, we'll write the ``PublisherBookListView`` view itself::
375
376    from django.shortcuts import get_object_or_404
377    from django.views.generic import ListView
378    from books.models import Book, Publisher
379
380    class PublisherBookListView(ListView):
381
382        context_object_name = "book_list"
383        template_name = "books/books_by_publisher.html",
384
385        def get_queryset(self):
386            publisher = get_object_or_404(Publisher, name__iexact=self.args[0])
387            return Book.objects.filter(publisher=publisher)
388
389As you can see, it's quite easy to add more logic to the queryset selection;
390if we wanted, we could use ``self.request.user`` to filter using the current
391user, or other more complex logic.
392
393We can also add the publisher into the context at the same time, so we can
394use it in the template::
395
396    class PublisherBookListView(ListView):
397
398        context_object_name = "book_list"
399        template_name = "books/books_by_publisher.html",
400
401        def get_queryset(self):
402            self.publisher = get_object_or_404(Publisher, name__iexact=self.args[0])
403            return Book.objects.filter(publisher=self.publisher)
404
405        def get_context_data(self, **kwargs):
406            # Call the base implementation first to get a context
407            context = super(PublisherBookListView, self).get_context_data(**kwargs)
408            # Add in the publisher
409            context['publisher'] = self.publisher
410            return context
411
412Performing extra work
413---------------------
414
415The last common pattern we'll look at involves doing some extra work before
416or after calling the generic view.
417
418Imagine we had a ``last_accessed`` field on our ``Author`` object that we were
419using to keep track of the last time anybody looked at that author::
420
421    # models.py
422
423    class Author(models.Model):
424        salutation = models.CharField(max_length=10)
425        first_name = models.CharField(max_length=30)
426        last_name = models.CharField(max_length=40)
427        email = models.EmailField()
428        headshot = models.ImageField(upload_to='/tmp')
429        last_accessed = models.DateTimeField()
430
431The generic ``DetailView`` class, of course, wouldn't know anything about this
432field, but once again we could easily write a custom view to keep that field
433updated.
434
435First, we'd need to add an author detail bit in the URLconf to point to a
436custom view:
437
438.. parsed-literal::
439
440    from books.views import AuthorDetailView
441
442    urlpatterns = patterns('',
443        #...
444        **(r'^authors/(?P<pk>\\d+)/$', AuthorDetailView.as_view()),**
445    )
446
447Then we'd write our new view -- ``get_object`` is the method that retrieves the
448object -- so we simply override it and wrap the call::
449
450    import datetime
451    from books.models import Author
452    from django.views.generic import DetailView
453    from django.shortcuts import get_object_or_404
454
455    class AuthorDetailView(DetailView):
456
457        queryset = Author.objects.all()
458
459        def get_object(self):
460            # Call the superclass
461            object = super(AuthorDetailView, self).get_object()
462            # Record the last accessed date
463            object.last_accessed = datetime.datetime.now()
464            object.save()
465            # Return the object
466            return object
467
468.. note::
469
470    This code won't actually work unless you create a
471    ``books/author_detail.html`` template.
472
473.. note::
474
475    The URLconf here uses the named group ``pk`` - this name is the default
476    name that ``DetailView`` uses to find the value of the primary key used to
477    filter the queryset.
478
479    If you want to change it, you'll need to do your own ``get()`` call
480    on ``self.queryset`` using the new named parameter from ``self.kwargs``.
481
482More than just HTML
483-------------------
484
485So far, we've been focusing on rendering templates to generate
486responses. However, that's not all generic views can do.
487
488Each generic view is composed out of a series of mixins, and each
489mixin contributes a little piece of the entire view. Some of these
490mixins -- such as
491:class:`~django.views.generic.base.TemplateResponseMixin` -- are
492specifically designed for rendering content to an HTML response using a
493template. However, you can write your own mixins that perform
494different rendering behavior.
495
496For example, a simple JSON mixin might look something like this::
497
498    from django import http
499    from django.utils import simplejson as json
500
501    class JSONResponseMixin(object):
502        def render_to_response(self, context):
503            "Returns a JSON response containing 'context' as payload"
504            return self.get_json_response(self.convert_context_to_json(context))
505
506        def get_json_response(self, content, **httpresponse_kwargs):
507            "Construct an `HttpResponse` object."
508            return http.HttpResponse(content,
509                                     content_type='application/json',
510                                     **httpresponse_kwargs)
511
512        def convert_context_to_json(self, context):
513            "Convert the context dictionary into a JSON object"
514            # Note: This is *EXTREMELY* naive; in reality, you'll need
515            # to do much more complex handling to ensure that arbitrary
516            # objects -- such as Django model instances or querysets
517            # -- can be serialized as JSON.
518            return json.dumps(context)
519
520Then, you could build a JSON-returning
521:class:`~django.views.generic.detail.DetailView` by mixing your
522:class:`JSONResponseMixin` with the
523:class:`~django.views.generic.detail.BaseDetailView` -- (the
524:class:`~django.views.generic.detail.DetailView` before template
525rendering behavior has been mixed in)::
526
527    class JSONDetailView(JSONResponseMixin, BaseDetailView):
528        pass
529
530This view can then be deployed in the same way as any other
531:class:`~django.views.generic.detail.DetailView`, with exactly the
532same behavior -- except for the format of the response.
533
534If you want to be really adventurous, you could even mix a
535:class:`~django.views.generic.detail.DetailView` subclass that is able
536to return *both* HTML and JSON content, depending on some property of
537the HTTP request, such as a query argument or a HTTP header. Just mix
538in both the :class:`JSONResponseMixin` and a
539:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,
540and override the implementation of :func:`render_to_response()` to defer
541to the appropriate subclass depending on the type of response that the user
542requested::
543
544    class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):
545        def render_to_response(self, context):
546            # Look for a 'format=json' GET argument
547            if self.request.GET.get('format','html') == 'json':
548                return JSONResponseMixin.render_to_response(self, context)
549            else:
550                return SingleObjectTemplateResponseMixin.render_to_response(self, context)
551
552Because of the way that Python resolves method overloading, the local
553:func:`render_to_response()` implementation will override the
554versions provided by :class:`JSONResponseMixin` and
555:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.
556
557Decorating class-based views
558============================
559
560.. highlightlang:: python
561
562The extension of class-based views isn't limited to using mixins. You
563can use also use decorators.
564
565Decorating in URLconf
566---------------------
567
568The simplest way of decorating class-based views is to decorate the
569result of the :meth:`~django.views.generic.base.View.as_view` method.
570The easiest place to do this is in the URLconf where you deploy your
571view::
572
573    from django.contrib.auth.decorators import login_required, permission_required
574    from django.views.generic import TemplateView
575
576    from .views import VoteView
577
578    urlpatterns = patterns('',
579        (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
580        (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
581    )
582
583This approach applies the decorator on a per-instance basis. If you
584want every instance of a view to be decorated, you need to take a
585different approach.
586
587Decorating the class
588--------------------
589
590To decorate every instance of a class-based view, you need to decorate
591the class definition itself. To do this you apply the decorator to the
592:meth:`~django.views.generic.base.View.dispatch` method of the class.
593
594A method on a class isn't quite the same as a standalone function, so
595you can't just apply a function decorator to the method -- you need to
596transform it into a method decorator first. The ``method_decorator``
597decorator transforms a function decorator into a method decorator so
598that it can be used on an instance method. For example::
599
600    from django.contrib.auth.decorators import login_required
601    from django.utils.decorators import method_decorator
602    from django.views.generic import TemplateView
603
604    class ProtectedView(TemplateView):
605        template_name = 'secret.html'
606
607        @method_decorator(login_required)
608        def dispatch(self, *args, **kwargs):
609            return super(ProtectedView, self).dispatch(*args, **kwargs)
610
611In this example, every instance of ``ProtectedView`` will have
612login protection.
613
614.. note::
615
616    ``method_decorator`` passes ``*args`` and ``**kwargs``
617    as parameters to the decorated method on the class. If your method
618    does not accept a compatible set of parameters it will raise a
619    ``TypeError`` exception.