tutorial03.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 simple Python function (or method, in the case of class-based
  29. views). Django will choose a view by examining the URL that's requested (to be
  30. precise, 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 simply 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 (described as regular expressions) to views.
  39. This tutorial provides basic instruction in the use of URLconfs, and you can
  40. refer to :mod:`django.core.urlresolvers` 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. .. snippet::
  46. :filename: 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.conf.urls.url` calls:
  56. .. snippet::
  57. :filename: polls/urls.py
  58. from django.conf.urls import url
  59. from . import views
  60. urlpatterns = [
  61. # ex: /polls/
  62. url(r'^$', views.index, name='index'),
  63. # ex: /polls/5/
  64. url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
  65. # ex: /polls/5/results/
  66. url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
  67. # ex: /polls/5/vote/
  68. url(r'^(?P<question_id>[0-9]+)/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 Web site -- 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 regular expressions in order. The
  78. :func:`~django.conf.urls.include` functions we are using simply reference
  79. other URLconfs. Note that the regular expressions for the
  80. :func:`~django.conf.urls.include` functions don't have a ``$`` (end-of-string
  81. match character) but rather a trailing slash. Whenever Django encounters
  82. :func:`~django.conf.urls.include`, it chops off whatever part of the URL
  83. matched up to that point and sends the remaining string to the included
  84. URLconf for further processing.
  85. The idea behind :func:`~django.conf.urls.include` is to make it easy to
  86. plug-and-play URLs. Since polls are in their own URLconf
  87. (``polls/urls.py``), they can be placed under "/polls/", or under
  88. "/fun_polls/", or under "/content/polls/", or any other path root, and the
  89. app will still work.
  90. Here's what happens if a user goes to "/polls/34/" in this system:
  91. * Django will find the match at ``'^polls/'``
  92. * Then, Django will strip off the matching text (``"polls/"``) and send the
  93. remaining text -- ``"34/"`` -- to the 'polls.urls' URLconf for
  94. further processing which matches ``r'^(?P<question_id>[0-9]+)/$'`` resulting in a
  95. call to the ``detail()`` view like so::
  96. detail(request=<HttpRequest object>, question_id='34')
  97. The ``question_id='34'`` part comes from ``(?P<question_id>[0-9]+)``. Using parentheses
  98. around a pattern "captures" the text matched by that pattern and sends it as an
  99. argument to the view function; ``?P<question_id>`` defines the name that will
  100. be used to identify the matched pattern; and ``[0-9]+`` is a regular expression to
  101. match a sequence of digits (i.e., a number).
  102. Because the URL patterns are regular expressions, there really is no limit on
  103. what you can do with them. And there's no need to add URL cruft such as
  104. ``.html`` -- unless you want to, in which case you can do something like
  105. this::
  106. url(r'^polls/latest\.html$', views.index),
  107. But, don't do that. It's silly.
  108. Write views that actually do something
  109. ======================================
  110. Each view is responsible for doing one of two things: returning an
  111. :class:`~django.http.HttpResponse` object containing the content for the
  112. requested page, or raising an exception such as :exc:`~django.http.Http404`. The
  113. rest is up to you.
  114. Your view can read records from a database, or not. It can use a template
  115. system such as Django's -- or a third-party Python template system -- or not.
  116. It can generate a PDF file, output XML, create a ZIP file on the fly, anything
  117. you want, using whatever Python libraries you want.
  118. All Django wants is that :class:`~django.http.HttpResponse`. Or an exception.
  119. Because it's convenient, let's use Django's own database API, which we covered
  120. in :doc:`Tutorial 2 </intro/tutorial02>`. Here's one stab at a new ``index()``
  121. view, which displays the latest 5 poll questions in the system, separated by
  122. commas, according to publication date:
  123. .. snippet::
  124. :filename: polls/views.py
  125. from django.http import HttpResponse
  126. from .models import Question
  127. def index(request):
  128. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  129. output = ', '.join([q.question_text for q in latest_question_list])
  130. return HttpResponse(output)
  131. # Leave the rest of the views (detail, results, vote) unchanged
  132. There's a problem here, though: the page's design is hard-coded in the view. If
  133. you want to change the way the page looks, you'll have to edit this Python code.
  134. So let's use Django's template system to separate the design from Python by
  135. creating a template that the view can use.
  136. First, create a directory called ``templates`` in your ``polls`` directory.
  137. Django will look for templates in there.
  138. Your project's :setting:`TEMPLATES` setting describes how Django will load and
  139. render templates. The default settings file configures a ``DjangoTemplates``
  140. backend whose :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` option is set to
  141. ``True``. By convention ``DjangoTemplates`` looks for a "templates"
  142. subdirectory in each of the :setting:`INSTALLED_APPS`.
  143. Within the ``templates`` directory you have just created, create another
  144. directory called ``polls``, and within that create a file called
  145. ``index.html``. In other words, your template should be at
  146. ``polls/templates/polls/index.html``. Because of how the ``app_directories``
  147. template loader works as described above, you can refer to this template within
  148. Django simply as ``polls/index.html``.
  149. .. admonition:: Template namespacing
  150. Now we *might* be able to get away with putting our templates directly in
  151. ``polls/templates`` (rather than creating another ``polls`` subdirectory),
  152. but it would actually be a bad idea. Django will choose the first template
  153. it finds whose name matches, and if you had a template with the same name
  154. in a *different* application, Django would be unable to distinguish between
  155. them. We need to be able to point Django at the right one, and the easiest
  156. way to ensure this is by *namespacing* them. That is, by putting those
  157. templates inside *another* directory named for the application itself.
  158. Put the following code in that template:
  159. .. snippet:: html+django
  160. :filename: polls/templates/polls/index.html
  161. {% if latest_question_list %}
  162. <ul>
  163. {% for question in latest_question_list %}
  164. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
  165. {% endfor %}
  166. </ul>
  167. {% else %}
  168. <p>No polls are available.</p>
  169. {% endif %}
  170. Now let's update our ``index`` view in ``polls/views.py`` to use the template:
  171. .. snippet::
  172. :filename: polls/views.py
  173. from django.http import HttpResponse
  174. from django.template import RequestContext, loader
  175. from .models import Question
  176. def index(request):
  177. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  178. template = loader.get_template('polls/index.html')
  179. context = RequestContext(request, {
  180. 'latest_question_list': latest_question_list,
  181. })
  182. return HttpResponse(template.render(context))
  183. That code loads the template called ``polls/index.html`` and passes it a
  184. context. The context is a dictionary mapping template variable names to Python
  185. objects.
  186. Load the page by pointing your browser at "/polls/", and you should see a
  187. bulleted-list containing the "What's up" question from :doc:`Tutorial 2
  188. </intro/tutorial02>`. The link points to the question's detail page.
  189. A shortcut: :func:`~django.shortcuts.render`
  190. --------------------------------------------
  191. It's a very common idiom to load a template, fill a context and return an
  192. :class:`~django.http.HttpResponse` object with the result of the rendered
  193. template. Django provides a shortcut. Here's the full ``index()`` view,
  194. rewritten:
  195. .. snippet::
  196. :filename: polls/views.py
  197. from django.shortcuts import render
  198. from .models import Question
  199. def index(request):
  200. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  201. context = {'latest_question_list': latest_question_list}
  202. return render(request, 'polls/index.html', context)
  203. Note that once we've done this in all these views, we no longer need to import
  204. :mod:`~django.template.loader`, :class:`~django.template.RequestContext` and
  205. :class:`~django.http.HttpResponse` (you'll want to keep ``HttpResponse`` if you
  206. still have the stub methods for ``detail``, ``results``, and ``vote``).
  207. The :func:`~django.shortcuts.render` function takes the request object as its
  208. first argument, a template name as its second argument and a dictionary as its
  209. optional third argument. It returns an :class:`~django.http.HttpResponse`
  210. object of the given template rendered with the given context.
  211. Raising a 404 error
  212. ===================
  213. Now, let's tackle the question detail view -- the page that displays the question text
  214. for a given poll. Here's the view:
  215. .. snippet::
  216. :filename: polls/views.py
  217. from django.http import Http404
  218. from django.shortcuts import render
  219. from .models import Question
  220. # ...
  221. def detail(request, question_id):
  222. try:
  223. question = Question.objects.get(pk=question_id)
  224. except Question.DoesNotExist:
  225. raise Http404("Question does not exist")
  226. return render(request, 'polls/detail.html', {'question': question})
  227. The new concept here: The view raises the :exc:`~django.http.Http404` exception
  228. if a question with the requested ID doesn't exist.
  229. We'll discuss what you could put in that ``polls/detail.html`` template a bit
  230. later, but if you'd like to quickly get the above example working, a file
  231. containing just:
  232. .. snippet:: html+django
  233. :filename: polls/templates/polls/detail.html
  234. {{ question }}
  235. will get you started for now.
  236. A shortcut: :func:`~django.shortcuts.get_object_or_404`
  237. -------------------------------------------------------
  238. It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get`
  239. and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
  240. provides a shortcut. Here's the ``detail()`` view, rewritten:
  241. .. snippet::
  242. :filename: polls/views.py
  243. from django.shortcuts import get_object_or_404, render
  244. from .models import Question
  245. # ...
  246. def detail(request, question_id):
  247. question = get_object_or_404(Question, pk=question_id)
  248. return render(request, 'polls/detail.html', {'question': question})
  249. The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
  250. as its first argument and an arbitrary number of keyword arguments, which it
  251. passes to the :meth:`~django.db.models.query.QuerySet.get` function of the
  252. model's manager. It raises :exc:`~django.http.Http404` if the object doesn't
  253. exist.
  254. .. admonition:: Philosophy
  255. Why do we use a helper function :func:`~django.shortcuts.get_object_or_404`
  256. instead of automatically catching the
  257. :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher
  258. level, or having the model API raise :exc:`~django.http.Http404` instead of
  259. :exc:`~django.core.exceptions.ObjectDoesNotExist`?
  260. Because that would couple the model layer to the view layer. One of the
  261. foremost design goals of Django is to maintain loose coupling. Some
  262. controlled coupling is introduced in the :mod:`django.shortcuts` module.
  263. There's also a :func:`~django.shortcuts.get_list_or_404` function, which works
  264. just as :func:`~django.shortcuts.get_object_or_404` -- except using
  265. :meth:`~django.db.models.query.QuerySet.filter` instead of
  266. :meth:`~django.db.models.query.QuerySet.get`. It raises
  267. :exc:`~django.http.Http404` if the list is empty.
  268. Use the template system
  269. =======================
  270. Back to the ``detail()`` view for our poll application. Given the context
  271. variable ``question``, here's what the ``polls/detail.html`` template might look
  272. like:
  273. .. snippet:: html+django
  274. :filename: polls/templates/polls/detail.html
  275. <h1>{{ question.question_text }}</h1>
  276. <ul>
  277. {% for choice in question.choice_set.all %}
  278. <li>{{ choice.choice_text }}</li>
  279. {% endfor %}
  280. </ul>
  281. The template system uses dot-lookup syntax to access variable attributes. In
  282. the example of ``{{ question.question_text }}``, first Django does a dictionary lookup
  283. on the object ``question``. Failing that, it tries an attribute lookup -- which
  284. works, in this case. If attribute lookup had failed, it would've tried a
  285. list-index lookup.
  286. Method-calling happens in the :ttag:`{% for %}<for>` loop:
  287. ``question.choice_set.all`` is interpreted as the Python code
  288. ``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is
  289. suitable for use in the :ttag:`{% for %}<for>` tag.
  290. See the :doc:`template guide </topics/templates>` for more about templates.
  291. Removing hardcoded URLs in templates
  292. ====================================
  293. Remember, when we wrote the link to a question in the ``polls/index.html``
  294. template, the link was partially hardcoded like this:
  295. .. code-block:: html+django
  296. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
  297. The problem with this hardcoded, tightly-coupled approach is that it becomes
  298. challenging to change URLs on projects with a lot of templates. However, since
  299. you defined the name argument in the :func:`~django.conf.urls.url` functions in
  300. the ``polls.urls`` module, you can remove a reliance on specific URL paths
  301. defined in your url configurations by using the ``{% url %}`` template tag:
  302. .. code-block:: html+django
  303. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
  304. The way this works is by looking up the URL definition as specified in the
  305. ``polls.urls`` module. You can see exactly where the URL name of 'detail' is
  306. defined below::
  307. ...
  308. # the 'name' value as called by the {% url %} template tag
  309. url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
  310. ...
  311. If you want to change the URL of the polls detail view to something else,
  312. perhaps to something like ``polls/specifics/12/`` instead of doing it in the
  313. template (or templates) you would change it in ``polls/urls.py``::
  314. ...
  315. # added the word 'specifics'
  316. url(r'^specifics/(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
  317. ...
  318. Namespacing URL names
  319. ======================
  320. The tutorial project has just one app, ``polls``. In real Django projects,
  321. there might be five, ten, twenty apps or more. How does Django differentiate
  322. the URL names between them? For example, the ``polls`` app has a ``detail``
  323. view, and so might an app on the same project that is for a blog. How does one
  324. make it so that Django knows which app view to create for a url when using the
  325. ``{% url %}`` template tag?
  326. The answer is to add namespaces to your URLconf. In the ``polls/urls.py``
  327. file, go ahead and add an ``app_name`` to set the application namespace:
  328. .. snippet::
  329. :filename: polls/urls.py
  330. from django.conf.urls import url
  331. app_name = 'polls'
  332. urlpatterns = [
  333. url(r'^$', views.index, name='index'),
  334. url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
  335. url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
  336. url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
  337. ]
  338. Now change your ``polls/index.html`` template from:
  339. .. snippet:: html+django
  340. :filename: polls/templates/polls/index.html
  341. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
  342. to point at the namespaced detail view:
  343. .. snippet:: html+django
  344. :filename: polls/templates/polls/index.html
  345. <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
  346. When you're comfortable with writing views, read :doc:`part 4 of this tutorial
  347. </intro/tutorial04>` to learn about simple form processing and generic views.