tutorial03.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. =====================================
  2. Writing your first Django app, part 3
  3. =====================================
  4. This tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off. We're
  5. continuing the Web-poll application and will focus on creating the public
  6. interface -- "views."
  7. Overview
  8. ========
  9. A view is a "type" of Web page in your Django application that generally serves
  10. a specific function and has a specific template. For example, in a blog
  11. application, you might have the following views:
  12. * Blog homepage -- displays the latest few entries.
  13. * Entry "detail" page -- permalink page for a single entry.
  14. * Year-based archive page -- displays all months with entries in the
  15. given year.
  16. * Month-based archive page -- displays all days with entries in the
  17. given month.
  18. * Day-based archive page -- displays all entries in the given day.
  19. * Comment action -- handles posting comments to a given entry.
  20. In our poll application, we'll have the following four views:
  21. * Question "index" page -- displays the latest few questions.
  22. * Question "detail" page -- displays a question text, with no results but
  23. with a form to vote.
  24. * Question "results" page -- displays results for a particular question.
  25. * Vote action -- handles voting for a particular choice in a particular
  26. question.
  27. In Django, web pages and other content are delivered by views. Each view is
  28. represented by a Python function (or method, in the case of class-based views).
  29. Django will choose a view by examining the URL that's requested (to be precise,
  30. the part of the URL after the domain name).
  31. Now in your time on the web you may have come across such beauties as
  32. "ME2/Sites/dirmod.asp?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B".
  33. You will be pleased to know that Django allows us much more elegant
  34. *URL patterns* than that.
  35. A URL pattern is the general form of a URL - for example:
  36. ``/newsarchive/<year>/<month>/``.
  37. To get from a URL to a view, Django uses what are known as 'URLconfs'. A
  38. URLconf maps URL patterns to views.
  39. This tutorial provides basic instruction in the use of URLconfs, and you can
  40. refer to :doc:`/topics/http/urls` for more information.
  41. Writing more views
  42. ==================
  43. Now let's add a few more views to ``polls/views.py``. These views are
  44. slightly different, because they take an argument:
  45. .. code-block:: python
  46. :caption: polls/views.py
  47. def detail(request, question_id):
  48. return HttpResponse("You're looking at question %s." % question_id)
  49. def results(request, question_id):
  50. response = "You're looking at the results of question %s."
  51. return HttpResponse(response % question_id)
  52. def vote(request, question_id):
  53. return HttpResponse("You're voting on question %s." % question_id)
  54. Wire these new views into the ``polls.urls`` module by adding the following
  55. :func:`~django.urls.path` calls:
  56. .. code-block:: python
  57. :caption: polls/urls.py
  58. from django.urls import path
  59. from . import views
  60. urlpatterns = [
  61. # ex: /polls/
  62. path('', views.index, name='index'),
  63. # ex: /polls/5/
  64. path('<int:question_id>/', views.detail, name='detail'),
  65. # ex: /polls/5/results/
  66. path('<int:question_id>/results/', views.results, name='results'),
  67. # ex: /polls/5/vote/
  68. path('<int:question_id>/vote/', views.vote, name='vote'),
  69. ]
  70. Take a look in your browser, at "/polls/34/". It'll run the ``detail()``
  71. method and display whatever ID you provide in the URL. Try
  72. "/polls/34/results/" and "/polls/34/vote/" too -- these will display the
  73. placeholder results and voting pages.
  74. When somebody requests a page from your website -- say, "/polls/34/", Django
  75. will load the ``mysite.urls`` Python module because it's pointed to by the
  76. :setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns``
  77. and traverses the patterns in order. After finding the match at ``'polls/'``,
  78. it strips off the matching text (``"polls/"``) and sends the remaining text --
  79. ``"34/"`` -- to the 'polls.urls' URLconf for further processing. There it
  80. matches ``'<int:question_id>/'``, resulting in a call to the ``detail()`` view
  81. like so::
  82. detail(request=<HttpRequest object>, question_id=34)
  83. The ``question_id=34`` part comes from ``<int:question_id>``. Using angle
  84. brackets "captures" part of the URL and sends it as a keyword argument to the
  85. view function. The ``:question_id>`` part of the string defines the name that
  86. will be used to identify the matched pattern, and the ``<int:`` part is a
  87. converter that determines what patterns should match this part of the URL path.
  88. There's no need to add URL cruft such as ``.html`` -- unless you want to, in
  89. which case you can do something like this::
  90. path('polls/latest.html', views.index),
  91. But, don't do that. It's silly.
  92. Write views that actually do something
  93. ======================================
  94. Each view is responsible for doing one of two things: returning an
  95. :class:`~django.http.HttpResponse` object containing the content for the
  96. requested page, or raising an exception such as :exc:`~django.http.Http404`. The
  97. rest is up to you.
  98. Your view can read records from a database, or not. It can use a template
  99. system such as Django's -- or a third-party Python template system -- or not.
  100. It can generate a PDF file, output XML, create a ZIP file on the fly, anything
  101. you want, using whatever Python libraries you want.
  102. All Django wants is that :class:`~django.http.HttpResponse`. Or an exception.
  103. Because it's convenient, let's use Django's own database API, which we covered
  104. in :doc:`Tutorial 2 </intro/tutorial02>`. Here's one stab at a new ``index()``
  105. view, which displays the latest 5 poll questions in the system, separated by
  106. commas, according to publication date:
  107. .. code-block:: python
  108. :caption: polls/views.py
  109. from django.http import HttpResponse
  110. from .models import Question
  111. def index(request):
  112. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  113. output = ', '.join([q.question_text for q in latest_question_list])
  114. return HttpResponse(output)
  115. # Leave the rest of the views (detail, results, vote) unchanged
  116. There's a problem here, though: the page's design is hard-coded in the view. If
  117. you want to change the way the page looks, you'll have to edit this Python code.
  118. So let's use Django's template system to separate the design from Python by
  119. creating a template that the view can use.
  120. First, create a directory called ``templates`` in your ``polls`` directory.
  121. Django will look for templates in there.
  122. Your project's :setting:`TEMPLATES` setting describes how Django will load and
  123. render templates. The default settings file configures a ``DjangoTemplates``
  124. backend whose :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` option is set to
  125. ``True``. By convention ``DjangoTemplates`` looks for a "templates"
  126. subdirectory in each of the :setting:`INSTALLED_APPS`.
  127. Within the ``templates`` directory you have just created, create another
  128. directory called ``polls``, and within that create a file called
  129. ``index.html``. In other words, your template should be at
  130. ``polls/templates/polls/index.html``. Because of how the ``app_directories``
  131. template loader works as described above, you can refer to this template within
  132. Django as ``polls/index.html``.
  133. .. admonition:: Template namespacing
  134. Now we *might* be able to get away with putting our templates directly in
  135. ``polls/templates`` (rather than creating another ``polls`` subdirectory),
  136. but it would actually be a bad idea. Django will choose the first template
  137. it finds whose name matches, and if you had a template with the same name
  138. in a *different* application, Django would be unable to distinguish between
  139. them. We need to be able to point Django at the right one, and the best
  140. way to ensure this is by *namespacing* them. That is, by putting those
  141. templates inside *another* directory named for the application itself.
  142. Put the following code in that template:
  143. .. code-block:: html+django
  144. :caption: polls/templates/polls/index.html
  145. {% if latest_question_list %}
  146. <ul>
  147. {% for question in latest_question_list %}
  148. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
  149. {% endfor %}
  150. </ul>
  151. {% else %}
  152. <p>No polls are available.</p>
  153. {% endif %}
  154. Now let's update our ``index`` view in ``polls/views.py`` to use the template:
  155. .. code-block:: python
  156. :caption: polls/views.py
  157. from django.http import HttpResponse
  158. from django.template import loader
  159. from .models import Question
  160. def index(request):
  161. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  162. template = loader.get_template('polls/index.html')
  163. context = {
  164. 'latest_question_list': latest_question_list,
  165. }
  166. return HttpResponse(template.render(context, request))
  167. That code loads the template called ``polls/index.html`` and passes it a
  168. context. The context is a dictionary mapping template variable names to Python
  169. objects.
  170. Load the page by pointing your browser at "/polls/", and you should see a
  171. bulleted-list containing the "What's up" question from :doc:`Tutorial 2
  172. </intro/tutorial02>`. The link points to the question's detail page.
  173. A shortcut: :func:`~django.shortcuts.render`
  174. --------------------------------------------
  175. It's a very common idiom to load a template, fill a context and return an
  176. :class:`~django.http.HttpResponse` object with the result of the rendered
  177. template. Django provides a shortcut. Here's the full ``index()`` view,
  178. rewritten:
  179. .. code-block:: python
  180. :caption: polls/views.py
  181. from django.shortcuts import render
  182. from .models import Question
  183. def index(request):
  184. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  185. context = {'latest_question_list': latest_question_list}
  186. return render(request, 'polls/index.html', context)
  187. Note that once we've done this in all these views, we no longer need to import
  188. :mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll
  189. want to keep ``HttpResponse`` if you still have the stub methods for ``detail``,
  190. ``results``, and ``vote``).
  191. The :func:`~django.shortcuts.render` function takes the request object as its
  192. first argument, a template name as its second argument and a dictionary as its
  193. optional third argument. It returns an :class:`~django.http.HttpResponse`
  194. object of the given template rendered with the given context.
  195. Raising a 404 error
  196. ===================
  197. Now, let's tackle the question detail view -- the page that displays the question text
  198. for a given poll. Here's the view:
  199. .. code-block:: python
  200. :caption: polls/views.py
  201. from django.http import Http404
  202. from django.shortcuts import render
  203. from .models import Question
  204. # ...
  205. def detail(request, question_id):
  206. try:
  207. question = Question.objects.get(pk=question_id)
  208. except Question.DoesNotExist:
  209. raise Http404("Question does not exist")
  210. return render(request, 'polls/detail.html', {'question': question})
  211. The new concept here: The view raises the :exc:`~django.http.Http404` exception
  212. if a question with the requested ID doesn't exist.
  213. We'll discuss what you could put in that ``polls/detail.html`` template a bit
  214. later, but if you'd like to quickly get the above example working, a file
  215. containing just:
  216. .. code-block:: html+django
  217. :caption: polls/templates/polls/detail.html
  218. {{ question }}
  219. will get you started for now.
  220. A shortcut: :func:`~django.shortcuts.get_object_or_404`
  221. -------------------------------------------------------
  222. It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get`
  223. and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
  224. provides a shortcut. Here's the ``detail()`` view, rewritten:
  225. .. code-block:: python
  226. :caption: polls/views.py
  227. from django.shortcuts import get_object_or_404, render
  228. from .models import Question
  229. # ...
  230. def detail(request, question_id):
  231. question = get_object_or_404(Question, pk=question_id)
  232. return render(request, 'polls/detail.html', {'question': question})
  233. The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
  234. as its first argument and an arbitrary number of keyword arguments, which it
  235. passes to the :meth:`~django.db.models.query.QuerySet.get` function of the
  236. model's manager. It raises :exc:`~django.http.Http404` if the object doesn't
  237. exist.
  238. .. admonition:: Philosophy
  239. Why do we use a helper function :func:`~django.shortcuts.get_object_or_404`
  240. instead of automatically catching the
  241. :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher
  242. level, or having the model API raise :exc:`~django.http.Http404` instead of
  243. :exc:`~django.core.exceptions.ObjectDoesNotExist`?
  244. Because that would couple the model layer to the view layer. One of the
  245. foremost design goals of Django is to maintain loose coupling. Some
  246. controlled coupling is introduced in the :mod:`django.shortcuts` module.
  247. There's also a :func:`~django.shortcuts.get_list_or_404` function, which works
  248. just as :func:`~django.shortcuts.get_object_or_404` -- except using
  249. :meth:`~django.db.models.query.QuerySet.filter` instead of
  250. :meth:`~django.db.models.query.QuerySet.get`. It raises
  251. :exc:`~django.http.Http404` if the list is empty.
  252. Use the template system
  253. =======================
  254. Back to the ``detail()`` view for our poll application. Given the context
  255. variable ``question``, here's what the ``polls/detail.html`` template might look
  256. like:
  257. .. code-block:: html+django
  258. :caption: polls/templates/polls/detail.html
  259. <h1>{{ question.question_text }}</h1>
  260. <ul>
  261. {% for choice in question.choice_set.all %}
  262. <li>{{ choice.choice_text }}</li>
  263. {% endfor %}
  264. </ul>
  265. The template system uses dot-lookup syntax to access variable attributes. In
  266. the example of ``{{ question.question_text }}``, first Django does a dictionary lookup
  267. on the object ``question``. Failing that, it tries an attribute lookup -- which
  268. works, in this case. If attribute lookup had failed, it would've tried a
  269. list-index lookup.
  270. Method-calling happens in the :ttag:`{% for %}<for>` loop:
  271. ``question.choice_set.all`` is interpreted as the Python code
  272. ``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is
  273. suitable for use in the :ttag:`{% for %}<for>` tag.
  274. See the :doc:`template guide </topics/templates>` for more about templates.
  275. Removing hardcoded URLs in templates
  276. ====================================
  277. Remember, when we wrote the link to a question in the ``polls/index.html``
  278. template, the link was partially hardcoded like this:
  279. .. code-block:: html+django
  280. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
  281. The problem with this hardcoded, tightly-coupled approach is that it becomes
  282. challenging to change URLs on projects with a lot of templates. However, since
  283. you defined the name argument in the :func:`~django.urls.path` functions in
  284. the ``polls.urls`` module, you can remove a reliance on specific URL paths
  285. defined in your url configurations by using the ``{% url %}`` template tag:
  286. .. code-block:: html+django
  287. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
  288. The way this works is by looking up the URL definition as specified in the
  289. ``polls.urls`` module. You can see exactly where the URL name of 'detail' is
  290. defined below::
  291. ...
  292. # the 'name' value as called by the {% url %} template tag
  293. path('<int:question_id>/', views.detail, name='detail'),
  294. ...
  295. If you want to change the URL of the polls detail view to something else,
  296. perhaps to something like ``polls/specifics/12/`` instead of doing it in the
  297. template (or templates) you would change it in ``polls/urls.py``::
  298. ...
  299. # added the word 'specifics'
  300. path('specifics/<int:question_id>/', views.detail, name='detail'),
  301. ...
  302. Namespacing URL names
  303. =====================
  304. The tutorial project has just one app, ``polls``. In real Django projects,
  305. there might be five, ten, twenty apps or more. How does Django differentiate
  306. the URL names between them? For example, the ``polls`` app has a ``detail``
  307. view, and so might an app on the same project that is for a blog. How does one
  308. make it so that Django knows which app view to create for a url when using the
  309. ``{% url %}`` template tag?
  310. The answer is to add namespaces to your URLconf. In the ``polls/urls.py``
  311. file, go ahead and add an ``app_name`` to set the application namespace:
  312. .. code-block:: python
  313. :caption: polls/urls.py
  314. from django.urls import path
  315. from . import views
  316. app_name = 'polls'
  317. urlpatterns = [
  318. path('', views.index, name='index'),
  319. path('<int:question_id>/', views.detail, name='detail'),
  320. path('<int:question_id>/results/', views.results, name='results'),
  321. path('<int:question_id>/vote/', views.vote, name='vote'),
  322. ]
  323. Now change your ``polls/index.html`` template from:
  324. .. code-block:: html+django
  325. :caption: polls/templates/polls/index.html
  326. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
  327. to point at the namespaced detail view:
  328. .. code-block:: html+django
  329. :caption: polls/templates/polls/index.html
  330. <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
  331. When you're comfortable with writing views, read :doc:`part 4 of this tutorial
  332. </intro/tutorial04>` to learn the basics about form processing and generic
  333. views.