mixins.txt 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. ===================================
  2. Using mixins with class-based views
  3. ===================================
  4. .. caution::
  5. This is an advanced topic. A working knowledge of :doc:`Django's
  6. class-based views<index>` is advised before exploring these
  7. techniques.
  8. Django's built-in class-based views provide a lot of functionality,
  9. but some of it you may want to use separately. For instance, you may
  10. want to write a view that renders a template to make the HTTP
  11. response, but you can't use
  12. :class:`~django.views.generic.base.TemplateView`; perhaps you need to
  13. render a template only on `POST`, with `GET` doing something else
  14. entirely. While you could use
  15. :class:`~django.template.response.TemplateResponse` directly, this
  16. will likely result in duplicate code.
  17. For this reason, Django also provides a number of mixins that provide
  18. more discrete functionality. Template rendering, for instance, is
  19. encapsulated in the
  20. :class:`~django.views.generic.base.TemplateResponseMixin`. The Django
  21. reference documentation contains :doc:`full documentation of all the
  22. mixins</ref/class-based-views/mixins>`.
  23. Context and template responses
  24. ==============================
  25. Two central mixins are provided that help in providing a consistent
  26. interface to working with templates in class-based views.
  27. :class:`~django.views.generic.base.TemplateResponseMixin`
  28. Every built in view which returns a
  29. :class:`~django.template.response.TemplateResponse` will call the
  30. :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
  31. method that :class:`TemplateResponseMixin` provides. Most of the time this
  32. will be called for you (for instance, it is called by the ``get()`` method
  33. implemented by both :class:`~django.views.generic.base.TemplateView` and
  34. :class:`~django.views.generic.base.DetailView`); similarly, it's unlikely
  35. that you'll need to override it, although if you want your response to
  36. return something not rendered via a Django template then you'll want to do
  37. it. For an example of this, see the :ref:`JSONResponseMixin example
  38. <jsonresponsemixin-example>`.
  39. ``render_to_response`` itself calls
  40. :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`,
  41. which by default will just look up
  42. :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` on
  43. the class-based view; two other mixins
  44. (:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`
  45. and
  46. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`)
  47. override this to provide more flexible defaults when dealing with actual
  48. objects.
  49. .. versionadded:: 1.5
  50. :class:`~django.views.generic.base.ContextMixin`
  51. Every built in view which needs context data, such as for rendering a
  52. template (including :class:`TemplateResponseMixin` above), should call
  53. :meth:`~django.views.generic.base.ContextMixin.get_context_data` passing
  54. any data they want to ensure is in there as keyword arguments.
  55. ``get_context_data`` returns a dictionary; in :class:`ContextMixin` it
  56. simply returns its keyword arguments, but it is common to override this to
  57. add more members to the dictionary.
  58. Building up Django's generic class-based views
  59. ==============================================
  60. Let's look at how two of Django's generic class-based views are built
  61. out of mixins providing discrete functionality. We'll consider
  62. :class:`~django.views.generic.detail.DetailView`, which renders a
  63. "detail" view of an object, and
  64. :class:`~django.views.generic.list.ListView`, which will render a list
  65. of objects, typically from a queryset, and optionally paginate
  66. them. This will introduce us to four mixins which between them provide
  67. useful functionality when working with either a single Django object,
  68. or multiple objects.
  69. There are also mixins involved in the generic edit views
  70. (:class:`~django.views.generic.edit.FormView`, and the model-specific
  71. views :class:`~django.views.generic.edit.CreateView`,
  72. :class:`~django.views.generic.edit.UpdateView` and
  73. :class:`~django.views.generic.edit.DeleteView`), and in the
  74. date-based generic views. These are
  75. covered in the :doc:`mixin reference
  76. documentation</ref/class-based-views/mixins>`.
  77. DetailView: working with a single Django object
  78. -----------------------------------------------
  79. To show the detail of an object, we basically need to do two things:
  80. we need to look up the object and then we need to make a
  81. :class:`TemplateResponse` with a suitable template, and that object as
  82. context.
  83. To get the object, :class:`~django.views.generic.detail.DetailView`
  84. relies on :class:`~django.views.generic.detail.SingleObjectMixin`,
  85. which provides a
  86. :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`
  87. method that figures out the object based on the URL of the request (it
  88. looks for ``pk`` and ``slug`` keyword arguments as declared in the
  89. URLConf, and looks the object up either from the
  90. :attr:`~django.views.generic.detail.SingleObjectMixin.model` attribute
  91. on the view, or the
  92. :attr:`~django.views.generic.detail.SingleObjectMixin.queryset`
  93. attribute if that's provided). :class:`SingleObjectMixin` also overrides
  94. :meth:`~django.views.generic.base.ContextMixin.get_context_data`,
  95. which is used across all Django's built in class-based views to supply
  96. context data for template renders.
  97. To then make a :class:`TemplateResponse`, :class:`DetailView` uses
  98. :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,
  99. which extends
  100. :class:`~django.views.generic.base.TemplateResponseMixin`, overriding
  101. :meth:`get_template_names()` as discussed above. It actually provides
  102. a fairly sophisticated set of options, but the main one that most
  103. people are going to use is
  104. ``<app_label>/<object_name>_detail.html``. The ``_detail`` part can be
  105. changed by setting
  106. :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`
  107. on a subclass to something else. (For instance, the :doc:`generic edit
  108. views<generic-editing>` use ``_form`` for create and update views, and
  109. ``_confirm_delete`` for delete views.)
  110. ListView: working with many Django objects
  111. ------------------------------------------
  112. Lists of objects follow roughly the same pattern: we need a (possibly
  113. paginated) list of objects, typically a :class:`QuerySet`, and then we need
  114. to make a :class:`TemplateResponse` with a suitable template using
  115. that list of objects.
  116. To get the objects, :class:`~django.views.generic.list.ListView` uses
  117. :class:`~django.views.generic.list.MultipleObjectMixin`, which
  118. provides both
  119. :meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`
  120. and
  121. :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`. Unlike
  122. with :class:`SingleObjectMixin`, there's no need to key off parts of
  123. the URL to figure out the queryset to work with, so the default just
  124. uses the
  125. :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` or
  126. :attr:`~django.views.generic.list.MultipleObjectMixin.model` attribute
  127. on the view class. A common reason to override
  128. :meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`
  129. here would be to dynamically vary the objects, such as depending on
  130. the current user or to exclude posts in the future for a blog.
  131. :class:`MultipleObjectMixin` also overrides
  132. :meth:`~django.views.generic.base.ContextMixin.get_context_data` to
  133. include appropriate context variables for pagination (providing
  134. dummies if pagination is disabled). It relies on ``object_list`` being
  135. passed in as a keyword argument, which :class:`ListView` arranges for
  136. it.
  137. To make a :class:`TemplateResponse`, :class:`ListView` then uses
  138. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`;
  139. as with :class:`SingleObjectTemplateResponseMixin` above, this
  140. overrides :meth:`get_template_names()` to provide :meth:`a range of
  141. options
  142. <~django.views.generic.list.MultipleObjectTempalteResponseMixin>`,
  143. with the most commonly-used being
  144. ``<app_label>/<object_name>_list.html``, with the ``_list`` part again
  145. being taken from the
  146. :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`
  147. attribute. (The date based generic views use suffixes such as ``_archive``,
  148. ``_archive_year`` and so on to use different templates for the various
  149. specialised date-based list views.)
  150. Using Django's class-based view mixins
  151. ======================================
  152. Now we've seen how Django's generic class-based views use the provided
  153. mixins, let's look at other ways we can combine them. Of course we're
  154. still going to be combining them with either built-in class-based
  155. views, or other generic class-based views, but there are a range of
  156. rarer problems you can solve than are provided for by Django out of
  157. the box.
  158. .. warning::
  159. Not all mixins can be used together, and not all generic class
  160. based views can be used with all other mixins. Here we present a
  161. few examples that do work; if you want to bring together other
  162. functionality then you'll have to consider interactions between
  163. attributes and methods that overlap between the different classes
  164. you're using, and how `method resolution order`_ will affect which
  165. versions of the methods will be called in what order.
  166. The reference documentation for Django's :doc:`class-based
  167. views</ref/class-based-views/index>` and :doc:`class-based view
  168. mixins</ref/class-based-views/mixins>` will help you in
  169. understanding which attributes and methods are likely to cause
  170. conflict between different classes and mixins.
  171. If in doubt, it's often better to back off and base your work on
  172. :class:`View` or :class:`TemplateView`, perhaps with
  173. :class:`SimpleObjectMixin` and
  174. :class:`MultipleObjectMixin`. Although you will probably end up
  175. writing more code, it is more likely to be clearly understandable
  176. to someone else coming to it later, and with fewer interactions to
  177. worry about you will save yourself some thinking. (Of course, you
  178. can always dip into Django's implementation of the generic class
  179. based views for inspiration on how to tackle problems.)
  180. .. _method resolution order: http://www.python.org/download/releases/2.3/mro/
  181. Using SingleObjectMixin with View
  182. ---------------------------------
  183. If we want to write a simple class-based view that responds only to
  184. ``POST``, we'll subclass :class:`~django.views.generic.base.View` and
  185. write a ``post()`` method in the subclass. However if we want our
  186. processing to work on a particular object, identified from the URL,
  187. we'll want the functionality provided by
  188. :class:`~django.views.generic.detail.SingleObjectMixin`.
  189. We'll demonstrate this with the publisher modelling we used in the
  190. :doc:`generic class-based views introduction<generic-display>`.
  191. .. code-block:: python
  192. # views.py
  193. from django.http import HttpResponseForbidden, HttpResponseRedirect
  194. from django.core.urlresolvers import reverse
  195. from django.views.generic import View
  196. from django.views.generic.detail import SingleObjectMixin
  197. from books.models import Author
  198. class RecordInterest(View, SingleObjectMixin):
  199. """Records the current user's interest in an author."""
  200. model = Author
  201. def post(self, request, *args, **kwargs):
  202. if not request.user.is_authenticated():
  203. return HttpResponseForbidden()
  204. # Look up the author we're interested in.
  205. self.object = self.get_object()
  206. # Actually record interest somehow here!
  207. return HttpResponseRedirect(reverse('author-detail', kwargs={'pk': self.object.pk}))
  208. In practice you'd probably want to record the interest in a key-value
  209. store rather than in a relational database, so we've left that bit
  210. out. The only bit of the view that needs to worry about using
  211. :class:`SingleObjectMixin` is where we want to look up the author
  212. we're interested in, which it just does with a simple call to
  213. ``self.get_object()``. Everything else is taken care of for us by the
  214. mixin.
  215. We can hook this into our URLs easily enough::
  216. # urls.py
  217. from books.views import RecordInterest
  218. urlpatterns = patterns('',
  219. #...
  220. url(r'^author/(?P<pk>\d+)/interest/$', RecordInterest.as_view(), name='author-interest'),
  221. )
  222. Note the ``pk`` named group, which
  223. :meth:`~django.views.generic.detail.SingleObjectMixin.get_object` uses
  224. to look up the :class:`Author` instance. You could also use a slug, or
  225. any of the other features of :class:`SingleObjectMixin`.
  226. Using SingleObjectMixin with ListView
  227. -------------------------------------
  228. :class:`~django.views.generic.list.ListView` provides built-in
  229. pagination, but you might want to paginate a list of objects that are
  230. all linked (by a foreign key) to another object. In our publishing
  231. example, you might want to paginate through all the books by a
  232. particular publisher.
  233. One way to do this is to combine :class:`ListView` with
  234. :class:`SingleObjectMixin`, so that the queryset for the paginated
  235. list of books can hang off the publisher found as the single
  236. object. In order to do this, we need to have two different querysets:
  237. **Publisher queryset for use in get_object**
  238. We'll set that up directly when we call :meth:`get_object()`.
  239. **Book queryset for use by ListView**
  240. We'll figure that out ourselves in :meth:`get_queryset()` so we
  241. can take into account the Publisher we're looking at.
  242. .. note::
  243. We have to think carefully about :meth:`get_context_data()`.
  244. Since both :class:`SingleObjectMixin` and :class:`ListView` will
  245. put things in the context data under the value of
  246. :attr:`context_object_name` if it's set, we'll instead explictly
  247. ensure the Publisher is in the context data. :class:`ListView`
  248. will add in the suitable ``page_obj`` and ``paginator`` for us
  249. providing we remember to call ``super()``.
  250. Now we can write a new :class:`PublisherDetail`::
  251. from django.views.generic import ListView
  252. from django.views.generic.detail import SingleObjectMixin
  253. from books.models import Publisher
  254. class PublisherDetail(SingleObjectMixin, ListView):
  255. paginate_by = 2
  256. template_name = "books/publisher_detail.html"
  257. def get_context_data(self, **kwargs):
  258. kwargs['publisher'] = self.object
  259. return super(PublisherDetail, self).get_context_data(**kwargs)
  260. def get_queryset(self):
  261. self.object = self.get_object(Publisher.objects.all())
  262. return self.object.book_set.all()
  263. Notice how we set ``self.object`` within :meth:`get_queryset` so we
  264. can use it again later in :meth:`get_context_data`. If you don't set
  265. :attr:`template_name`, the template will default to the normal
  266. :class:`ListView` choice, which in this case would be
  267. ``"books/book_list.html"`` because it's a list of books;
  268. :class:`ListView` knows nothing about :class:`SingleObjectMixin`, so
  269. it doesn't have any clue this view is anything to do with a Publisher.
  270. .. highlightlang:: html+django
  271. The ``paginate_by`` is deliberately small in the example so you don't
  272. have to create lots of books to see the pagination working! Here's the
  273. template you'd want to use::
  274. {% extends "base.html" %}
  275. {% block content %}
  276. <h2>Publisher {{ publisher.name }}</h2>
  277. <ol>
  278. {% for book in page_obj %}
  279. <li>{{ book.title }}</li>
  280. {% endfor %}
  281. </ol>
  282. <div class="pagination">
  283. <span class="step-links">
  284. {% if page_obj.has_previous %}
  285. <a href="?page={{ page_obj.previous_page_number }}">previous</a>
  286. {% endif %}
  287. <span class="current">
  288. Page {{ page_obj.number }} of {{ paginator.num_pages }}.
  289. </span>
  290. {% if page_obj.has_next %}
  291. <a href="?page={{ page_obj.next_page_number }}">next</a>
  292. {% endif %}
  293. </span>
  294. </div>
  295. {% endblock %}
  296. Avoid anything more complex
  297. ===========================
  298. Generally you can use
  299. :class:`~django.views.generic.base.TemplateResponseMixin` and
  300. :class:`~django.views.generic.detail.SingleObjectMixin` when you need
  301. their functionality. As shown above, with a bit of care you can even
  302. combine :class:`SingleObjectMixin` with
  303. :class:`~django.views.generic.list.ListView`. However things get
  304. increasingly complex as you try to do so, and a good rule of thumb is:
  305. .. hint::
  306. Each of your views should use only mixins or views from one of the
  307. groups of generic class-based views: :doc:`detail,
  308. list<generic-display>`, :doc:`editing<generic-editing>` and
  309. date. For example it's fine to combine
  310. :class:`TemplateView` (built in view) with
  311. :class:`MultipleObjectMixin` (generic list), but you're likely to
  312. have problems combining :class:`SingleObjectMixin` (generic
  313. detail) with :class:`MultipleObjectMixin` (generic list).
  314. To show what happens when you try to get more sophisticated, we show
  315. an example that sacrifices readability and maintainability when there
  316. is a simpler solution. First, let's look at a naive attempt to combine
  317. :class:`~django.views.generic.detail.DetailView` with
  318. :class:`~django.views.generic.edit.FormMixin` to enable use to
  319. ``POST`` a Django :class:`Form` to the same URL as we're displaying an
  320. object using :class:`DetailView`.
  321. Using FormMixin with DetailView
  322. -------------------------------
  323. Think back to our earlier example of using :class:`View` and
  324. :class:`SingleObjectMixin` together. We were recording a user's
  325. interest in a particular author; say now that we want to let them
  326. leave a message saying why they like them. Again, let's assume we're
  327. not going to store this in a relational database but instead in
  328. something more esoteric that we won't worry about here.
  329. At this point it's natural to reach for a :class:`Form` to encapsulate
  330. the information sent from the user's browser to Django. Say also that
  331. we're heavily invested in `REST`_, so we want to use the same URL for
  332. displaying the author as for capturing the message from the
  333. user. Let's rewrite our :class:`AuthorDetailView` to do that.
  334. .. _REST: http://en.wikipedia.org/wiki/Representational_state_transfer
  335. We'll keep the ``GET`` handling from :class:`DetailView`, although
  336. we'll have to add a :class:`Form` into the context data so we can
  337. render it in the template. We'll also want to pull in form processing
  338. from :class:`~django.views.generic.edit.FormMixin`, and write a bit of
  339. code so that on ``POST`` the form gets called appropriately.
  340. .. note::
  341. We use :class:`FormMixin` and implement :meth:`post()` ourselves
  342. rather than try to mix :class:`DetailView` with :class:`FormView`
  343. (which provides a suitable :meth:`post()` already) because both of
  344. the views implement :meth:`get()`, and things would get much more
  345. confusing.
  346. .. highlightlang:: python
  347. Our new :class:`AuthorDetail` looks like this::
  348. # CAUTION: you almost certainly do not want to do this.
  349. # It is provided as part of a discussion of problems you can
  350. # run into when combining different generic class-based view
  351. # functionality that is not designed to be used together.
  352. from django import forms
  353. from django.http import HttpResponseForbidden
  354. from django.core.urlresolvers import reverse
  355. from django.views.generic import DetailView
  356. from django.views.generic.edit import FormMixin
  357. class AuthorInterestForm(forms.Form):
  358. message = forms.CharField()
  359. class AuthorDetail(DetailView, FormMixin):
  360. model = Author
  361. form_class = AuthorInterestForm
  362. def get_success_url(self):
  363. return reverse(
  364. 'author-detail',
  365. kwargs = {'pk': self.object.pk},
  366. )
  367. def get_context_data(self, **kwargs):
  368. form_class = self.get_form_class()
  369. form = self.get_form(form_class)
  370. context = {
  371. 'form': form
  372. }
  373. context.update(kwargs)
  374. return super(AuthorDetail, self).get_context_data(**context)
  375. def post(self, request, *args, **kwargs):
  376. form_class = self.get_form_class()
  377. form = self.get_form(form_class)
  378. if form.is_valid():
  379. return self.form_valid(form)
  380. else:
  381. return self.form_invalid(form)
  382. def form_valid(self, form):
  383. if not self.request.user.is_authenticated():
  384. return HttpResponseForbidden()
  385. self.object = self.get_object()
  386. # record the interest using the message in form.cleaned_data
  387. return super(AuthorDetail, self).form_valid(form)
  388. :meth:`get_success_url()` is just providing somewhere to redirect to,
  389. which gets used in the default implementation of
  390. :meth:`form_valid()`. We have to provide our own :meth:`post()` as
  391. noted earlier, and override :meth:`get_context_data()` to make the
  392. :class:`Form` available in the context data.
  393. A better solution
  394. -----------------
  395. It should be obvious that the number of subtle interactions between
  396. :class:`FormMixin` and :class:`DetailView` is already testing our
  397. ability to manage things. It's unlikely you'd want to write this kind
  398. of class yourself.
  399. In this case, it would be fairly easy to just write the :meth:`post()`
  400. method yourself, keeping :class:`DetailView` as the only generic
  401. functionality, although writing :class:`Form` handling code involves a
  402. lot of duplication.
  403. Alternatively, it would still be easier than the above approach to
  404. have a separate view for processing the form, which could use
  405. :class:`~django.views.generic.edit.FormView` distinct from
  406. :class:`DetailView` without concerns.
  407. An alternative better solution
  408. ------------------------------
  409. What we're really trying to do here is to use two different class
  410. based views from the same URL. So why not do just that? We have a very
  411. clear division here: ``GET`` requests should get the
  412. :class:`DetailView` (with the :class:`Form` added to the context
  413. data), and ``POST`` requests should get the :class:`FormView`. Let's
  414. set up those views first.
  415. The :class:`AuthorDisplay` view is almost the same as :ref:`when we
  416. first introduced AuthorDetail<generic-views-extra-work>`; we have to
  417. write our own :meth:`get_context_data()` to make the
  418. :class:`AuthorInterestForm` available to the template. We'll skip the
  419. :meth:`get_object()` override from before for clarity.
  420. .. code-block:: python
  421. from django.views.generic import DetailView
  422. from django import forms
  423. from books.models import Author
  424. class AuthorInterestForm(forms.Form):
  425. message = forms.CharField()
  426. class AuthorDisplay(DetailView):
  427. queryset = Author.objects.all()
  428. def get_context_data(self, **kwargs):
  429. context = {
  430. 'form': AuthorInterestForm(),
  431. }
  432. context.update(kwargs)
  433. return super(AuthorDisplay, self).get_context_data(**context)
  434. Then the :class:`AuthorInterest` is a simple :class:`FormView`, but we
  435. have to bring in :class:`SingleObjectMixin` so we can find the author
  436. we're talking about, and we have to remember to set
  437. :attr:`template_name` to ensure that form errors will render the same
  438. template as :class:`AuthorDisplay` is using on ``GET``.
  439. .. code-block:: python
  440. from django.views.generic import FormView
  441. from django.views.generic.detail import SingleObjectMixin
  442. class AuthorInterest(FormView, SingleObjectMixin):
  443. template_name = 'books/author_detail.html'
  444. form_class = AuthorInterestForm
  445. model = Author
  446. def get_context_data(self, **kwargs):
  447. context = {
  448. 'object': self.get_object(),
  449. }
  450. return super(AuthorInterest, self).get_context_data(**context)
  451. def get_success_url(self):
  452. return reverse(
  453. 'author-detail',
  454. kwargs = {'pk': self.object.pk},
  455. )
  456. def form_valid(self, form):
  457. if not self.request.user.is_authenticated():
  458. return HttpResponseForbidden()
  459. self.object = self.get_object()
  460. # record the interest using the message in form.cleaned_data
  461. return super(AuthorInterest, self).form_valid(form)
  462. Finally we bring this together in a new :class:`AuthorDetail` view. We
  463. already know that calling :meth:`as_view()` on a class-based view
  464. gives us something that behaves exactly like a function based view, so
  465. we can do that at the point we choose between the two subviews.
  466. You can of course pass through keyword arguments to :meth:`as_view()`
  467. in the same way you would in your URLconf, such as if you wanted the
  468. :class:`AuthorInterest` behaviour to also appear at another URL but
  469. using a different template.
  470. .. code-block:: python
  471. from django.views.generic import View
  472. class AuthorDetail(View):
  473. def get(self, request, *args, **kwargs):
  474. view = AuthorDisplay.as_view()
  475. return view(request, *args, **kwargs)
  476. def post(self, request, *args, **kwargs):
  477. view = AuthorInterest.as_view()
  478. return view(request, *args, **kwargs)
  479. This approach can also be used with any other generic class-based
  480. views or your own class-based views inheriting directly from
  481. :class:`View` or :class:`TemplateView`, as it keeps the different
  482. views as separate as possible.
  483. .. _jsonresponsemixin-example:
  484. More than just HTML
  485. ===================
  486. Where class based views shine is when you want to do the same thing many times.
  487. Suppose you're writing an API, and every view should return JSON instead of
  488. rendered HTML.
  489. We can create a mixin class to use in all of our views, handling the
  490. conversion to JSON once.
  491. For example, a simple JSON mixin might look something like this::
  492. import json
  493. from django.http import HttpResponse
  494. class JSONResponseMixin(object):
  495. """
  496. A mixin that can be used to render a JSON response.
  497. """
  498. response_class = HttpResponse
  499. def render_to_response(self, context, **response_kwargs):
  500. """
  501. Returns a JSON response, transforming 'context' to make the payload.
  502. """
  503. response_kwargs['content_type'] = 'application/json'
  504. return self.response_class(
  505. self.convert_context_to_json(context),
  506. **response_kwargs
  507. )
  508. def convert_context_to_json(self, context):
  509. "Convert the context dictionary into a JSON object"
  510. # Note: This is *EXTREMELY* naive; in reality, you'll need
  511. # to do much more complex handling to ensure that arbitrary
  512. # objects -- such as Django model instances or querysets
  513. # -- can be serialized as JSON.
  514. return json.dumps(context)
  515. Now we mix this into the base TemplateView::
  516. from django.views.generic import TemplateView
  517. class JSONView(JSONResponseMixin, TemplateView):
  518. pass
  519. Equally we could use our mixin with one of the generic views. We can make our
  520. own version of :class:`~django.views.generic.detail.DetailView` by mixing
  521. :class:`JSONResponseMixin` with the
  522. :class:`~django.views.generic.detail.BaseDetailView` -- (the
  523. :class:`~django.views.generic.detail.DetailView` before template
  524. rendering behavior has been mixed in)::
  525. class JSONDetailView(JSONResponseMixin, BaseDetailView):
  526. pass
  527. This view can then be deployed in the same way as any other
  528. :class:`~django.views.generic.detail.DetailView`, with exactly the
  529. same behavior -- except for the format of the response.
  530. If you want to be really adventurous, you could even mix a
  531. :class:`~django.views.generic.detail.DetailView` subclass that is able
  532. to return *both* HTML and JSON content, depending on some property of
  533. the HTTP request, such as a query argument or a HTTP header. Just mix
  534. in both the :class:`JSONResponseMixin` and a
  535. :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,
  536. and override the implementation of :func:`render_to_response()` to defer
  537. to the appropriate subclass depending on the type of response that the user
  538. requested::
  539. class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):
  540. def render_to_response(self, context):
  541. # Look for a 'format=json' GET argument
  542. if self.request.GET.get('format','html') == 'json':
  543. return JSONResponseMixin.render_to_response(self, context)
  544. else:
  545. return SingleObjectTemplateResponseMixin.render_to_response(self, context)
  546. Because of the way that Python resolves method overloading, the local
  547. ``render_to_response()`` implementation will override the versions provided by
  548. :class:`JSONResponseMixin` and
  549. :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.