Debian Codegraph @

docs/intro/tutorial03.txt

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