tutorial03.txt 18 KB

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