tutorial03.txt 18 KB

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