mixins.txt 30 KB

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