tutorial03.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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 = {
  169. "latest_question_list": latest_question_list,
  170. }
  171. return HttpResponse(template.render(context, request))
  172. That code loads the template called ``polls/index.html`` and passes it a
  173. context. The context is a dictionary mapping template variable names to Python
  174. objects.
  175. Load the page by pointing your browser at "/polls/", and you should see a
  176. bulleted-list containing the "What's up" question from :doc:`Tutorial 2
  177. </intro/tutorial02>`. The link points to the question's detail page.
  178. A shortcut: :func:`~django.shortcuts.render`
  179. --------------------------------------------
  180. It's a very common idiom to load a template, fill a context and return an
  181. :class:`~django.http.HttpResponse` object with the result of the rendered
  182. template. Django provides a shortcut. Here's the full ``index()`` view,
  183. rewritten:
  184. .. code-block:: python
  185. :caption: ``polls/views.py``
  186. from django.shortcuts import render
  187. from .models import Question
  188. def index(request):
  189. latest_question_list = Question.objects.order_by("-pub_date")[:5]
  190. context = {"latest_question_list": latest_question_list}
  191. return render(request, "polls/index.html", context)
  192. Note that once we've done this in all these views, we no longer need to import
  193. :mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll
  194. want to keep ``HttpResponse`` if you still have the stub methods for ``detail``,
  195. ``results``, and ``vote``).
  196. The :func:`~django.shortcuts.render` function takes the request object as its
  197. first argument, a template name as its second argument and a dictionary as its
  198. optional third argument. It returns an :class:`~django.http.HttpResponse`
  199. object of the given template rendered with the given context.
  200. Raising a 404 error
  201. ===================
  202. Now, let's tackle the question detail view -- the page that displays the question text
  203. for a given poll. Here's the view:
  204. .. code-block:: python
  205. :caption: ``polls/views.py``
  206. from django.http import Http404
  207. from django.shortcuts import render
  208. from .models import Question
  209. # ...
  210. def detail(request, question_id):
  211. try:
  212. question = Question.objects.get(pk=question_id)
  213. except Question.DoesNotExist:
  214. raise Http404("Question does not exist")
  215. return render(request, "polls/detail.html", {"question": question})
  216. The new concept here: The view raises the :exc:`~django.http.Http404` exception
  217. if a question with the requested ID doesn't exist.
  218. We'll discuss what you could put in that ``polls/detail.html`` template a bit
  219. later, but if you'd like to quickly get the above example working, a file
  220. containing just:
  221. .. code-block:: html+django
  222. :caption: ``polls/templates/polls/detail.html``
  223. {{ question }}
  224. will get you started for now.
  225. A shortcut: :func:`~django.shortcuts.get_object_or_404`
  226. -------------------------------------------------------
  227. It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get`
  228. and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
  229. provides a shortcut. Here's the ``detail()`` view, rewritten:
  230. .. code-block:: python
  231. :caption: ``polls/views.py``
  232. from django.shortcuts import get_object_or_404, render
  233. from .models import Question
  234. # ...
  235. def detail(request, question_id):
  236. question = get_object_or_404(Question, pk=question_id)
  237. return render(request, "polls/detail.html", {"question": question})
  238. The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
  239. as its first argument and an arbitrary number of keyword arguments, which it
  240. passes to the :meth:`~django.db.models.query.QuerySet.get` function of the
  241. model's manager. It raises :exc:`~django.http.Http404` if the object doesn't
  242. exist.
  243. .. admonition:: Philosophy
  244. Why do we use a helper function :func:`~django.shortcuts.get_object_or_404`
  245. instead of automatically catching the
  246. :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher
  247. level, or having the model API raise :exc:`~django.http.Http404` instead of
  248. :exc:`~django.core.exceptions.ObjectDoesNotExist`?
  249. Because that would couple the model layer to the view layer. One of the
  250. foremost design goals of Django is to maintain loose coupling. Some
  251. controlled coupling is introduced in the :mod:`django.shortcuts` module.
  252. There's also a :func:`~django.shortcuts.get_list_or_404` function, which works
  253. just as :func:`~django.shortcuts.get_object_or_404` -- except using
  254. :meth:`~django.db.models.query.QuerySet.filter` instead of
  255. :meth:`~django.db.models.query.QuerySet.get`. It raises
  256. :exc:`~django.http.Http404` if the list is empty.
  257. Use the template system
  258. =======================
  259. Back to the ``detail()`` view for our poll application. Given the context
  260. variable ``question``, here's what the ``polls/detail.html`` template might look
  261. like:
  262. .. code-block:: html+django
  263. :caption: ``polls/templates/polls/detail.html``
  264. <h1>{{ question.question_text }}</h1>
  265. <ul>
  266. {% for choice in question.choice_set.all %}
  267. <li>{{ choice.choice_text }}</li>
  268. {% endfor %}
  269. </ul>
  270. The template system uses dot-lookup syntax to access variable attributes. In
  271. the example of ``{{ question.question_text }}``, first Django does a dictionary lookup
  272. on the object ``question``. Failing that, it tries an attribute lookup -- which
  273. works, in this case. If attribute lookup had failed, it would've tried a
  274. list-index lookup.
  275. Method-calling happens in the :ttag:`{% for %}<for>` loop:
  276. ``question.choice_set.all`` is interpreted as the Python code
  277. ``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is
  278. suitable for use in the :ttag:`{% for %}<for>` tag.
  279. See the :doc:`template guide </topics/templates>` for more about templates.
  280. Removing hardcoded URLs in templates
  281. ====================================
  282. Remember, when we wrote the link to a question in the ``polls/index.html``
  283. template, the link was partially hardcoded like this:
  284. .. code-block:: html+django
  285. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
  286. The problem with this hardcoded, tightly-coupled approach is that it becomes
  287. challenging to change URLs on projects with a lot of templates. However, since
  288. you defined the ``name`` argument in the :func:`~django.urls.path` functions in
  289. the ``polls.urls`` module, you can remove a reliance on specific URL paths
  290. defined in your url configurations by using the ``{% url %}`` template tag:
  291. .. code-block:: html+django
  292. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
  293. The way this works is by looking up the URL definition as specified in the
  294. ``polls.urls`` module. You can see exactly where the URL name of 'detail' is
  295. defined below::
  296. ...
  297. # the 'name' value as called by the {% url %} template tag
  298. path("<int:question_id>/", views.detail, name="detail"),
  299. ...
  300. If you want to change the URL of the polls detail view to something else,
  301. perhaps to something like ``polls/specifics/12/`` instead of doing it in the
  302. template (or templates) you would change it in ``polls/urls.py``::
  303. ...
  304. # added the word 'specifics'
  305. path("specifics/<int:question_id>/", views.detail, name="detail"),
  306. ...
  307. Namespacing URL names
  308. =====================
  309. The tutorial project has just one app, ``polls``. In real Django projects,
  310. there might be five, ten, twenty apps or more. How does Django differentiate
  311. the URL names between them? For example, the ``polls`` app has a ``detail``
  312. view, and so might an app on the same project that is for a blog. How does one
  313. make it so that Django knows which app view to create for a url when using the
  314. ``{% url %}`` template tag?
  315. The answer is to add namespaces to your URLconf. In the ``polls/urls.py``
  316. file, go ahead and add an ``app_name`` to set the application namespace:
  317. .. code-block:: python
  318. :caption: ``polls/urls.py``
  319. from django.urls import path
  320. from . import views
  321. app_name = "polls"
  322. urlpatterns = [
  323. path("", views.index, name="index"),
  324. path("<int:question_id>/", views.detail, name="detail"),
  325. path("<int:question_id>/results/", views.results, name="results"),
  326. path("<int:question_id>/vote/", views.vote, name="vote"),
  327. ]
  328. Now change your ``polls/index.html`` template from:
  329. .. code-block:: html+django
  330. :caption: ``polls/templates/polls/index.html``
  331. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
  332. to point at the namespaced detail view:
  333. .. code-block:: html+django
  334. :caption: ``polls/templates/polls/index.html``
  335. <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
  336. When you're comfortable with writing views, read :doc:`part 4 of this tutorial
  337. </intro/tutorial04>` to learn the basics about form processing and generic
  338. views.