tutorial03.txt 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. Philosophy
  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. Write your first view
  42. =====================
  43. Let's write the first view. Open the file ``polls/views.py``
  44. and put the following Python code in it::
  45. from django.http import HttpResponse
  46. def index(request):
  47. return HttpResponse("Hello, world. You're at the polls index.")
  48. This is the simplest view possible in Django. To call the view, we need to map
  49. it to a URL - and for this we need a URLconf.
  50. To create a URLconf in the polls directory, create a file called ``urls.py``.
  51. Your app directory should now look like::
  52. polls/
  53. __init__.py
  54. admin.py
  55. models.py
  56. tests.py
  57. urls.py
  58. views.py
  59. In the ``polls/urls.py`` file include the following code:
  60. .. snippet::
  61. :filename: polls/urls.py
  62. from django.conf.urls import patterns, url
  63. from polls import views
  64. urlpatterns = patterns('',
  65. url(r'^$', views.index, name='index')
  66. )
  67. The next step is to point the root URLconf at the ``polls.urls`` module. In
  68. ``mysite/urls.py`` insert an :func:`~django.conf.urls.include`, leaving you
  69. with:
  70. .. snippet::
  71. :filename: mysite/urls.py
  72. from django.conf.urls import patterns, include, url
  73. from django.contrib import admin
  74. urlpatterns = patterns('',
  75. url(r'^polls/', include('polls.urls')),
  76. url(r'^admin/', include(admin.site.urls)),
  77. )
  78. .. admonition:: Doesn't match what you see?
  79. If you're seeing ``admin.autodiscover()`` before the definition of
  80. ``urlpatterns``, you're probably using a version of Django that doesn't
  81. match this tutorial version. You'll want to either switch to the older
  82. tutorial or the newer Django version.
  83. You have now wired an ``index`` view into the URLconf. Go to
  84. http://localhost:8000/polls/ in your browser, and you should see the text
  85. "*Hello, world. You're at the polls index.*", which you defined in the
  86. ``index`` view.
  87. The :func:`~django.conf.urls.url` function is passed four arguments, two
  88. required: ``regex`` and ``view``, and two optional: ``kwargs``, and ``name``.
  89. At this point, it's worth reviewing what these arguments are for.
  90. :func:`~django.conf.urls.url` argument: regex
  91. ---------------------------------------------
  92. The term "regex" is a commonly used short form meaning "regular expression",
  93. which is a syntax for matching patterns in strings, or in this case, url
  94. patterns. Django starts at the first regular expression and makes its way down
  95. the list, comparing the requested URL against each regular expression until it
  96. finds one that matches.
  97. Note that these regular expressions do not search GET and POST parameters, or
  98. the domain name. For example, in a request to
  99. ``http://www.example.com/myapp/``, the URLconf will look for ``myapp/``. In a
  100. request to ``http://www.example.com/myapp/?page=3``, the URLconf will also
  101. look for ``myapp/``.
  102. If you need help with regular expressions, see `Wikipedia's entry`_ and the
  103. documentation of the :mod:`re` module. Also, the O'Reilly book "Mastering
  104. Regular Expressions" by Jeffrey Friedl is fantastic. In practice, however,
  105. you don't need to be an expert on regular expressions, as you really only need
  106. to know how to capture simple patterns. In fact, complex regexes can have poor
  107. lookup performance, so you probably shouldn't rely on the full power of regexes.
  108. Finally, a performance note: these regular expressions are compiled the first
  109. time the URLconf module is loaded. They're super fast (as long as the lookups
  110. aren't too complex as noted above).
  111. .. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression
  112. :func:`~django.conf.urls.url` argument: view
  113. --------------------------------------------
  114. When Django finds a regular expression match, Django calls the specified view
  115. function, with an :class:`~django.http.HttpRequest` object as the first
  116. argument and any “captured” values from the regular expression as other
  117. arguments. If the regex uses simple captures, values are passed as positional
  118. arguments; if it uses named captures, values are passed as keyword arguments.
  119. We'll give an example of this in a bit.
  120. :func:`~django.conf.urls.url` argument: kwargs
  121. ----------------------------------------------
  122. Arbitrary keyword arguments can be passed in a dictionary to the target view. We
  123. aren't going to use this feature of Django in the tutorial.
  124. :func:`~django.conf.urls.url` argument: name
  125. ---------------------------------------------
  126. Naming your URL lets you refer to it unambiguously from elsewhere in Django
  127. especially templates. This powerful feature allows you to make global changes
  128. to the url patterns of your project while only touching a single file.
  129. Writing more views
  130. ==================
  131. Now let's add a few more views to ``polls/views.py``. These views are
  132. slightly different, because they take an argument:
  133. .. snippet::
  134. :filename: polls/views.py
  135. def detail(request, question_id):
  136. return HttpResponse("You're looking at question %s." % question_id)
  137. def results(request, question_id):
  138. response = "You're looking at the results of question %s."
  139. return HttpResponse(response % question_id)
  140. def vote(request, question_id):
  141. return HttpResponse("You're voting on question %s." % question_id)
  142. Wire these new views into the ``polls.urls`` module by adding the following
  143. :func:`~django.conf.urls.url` calls:
  144. .. snippet::
  145. :filename: polls/urls.py
  146. from django.conf.urls import patterns, url
  147. from polls import views
  148. urlpatterns = patterns('',
  149. # ex: /polls/
  150. url(r'^$', views.index, name='index'),
  151. # ex: /polls/5/
  152. url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'),
  153. # ex: /polls/5/results/
  154. url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
  155. # ex: /polls/5/vote/
  156. url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
  157. )
  158. Take a look in your browser, at "/polls/34/". It'll run the ``detail()``
  159. method and display whatever ID you provide in the URL. Try
  160. "/polls/34/results/" and "/polls/34/vote/" too -- these will display the
  161. placeholder results and voting pages.
  162. When somebody requests a page from your Web site -- say, "/polls/34/", Django
  163. will load the ``mysite.urls`` Python module because it's pointed to by the
  164. :setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns``
  165. and traverses the regular expressions in order. The
  166. :func:`~django.conf.urls.include` functions we are using simply reference
  167. other URLconfs. Note that the regular expressions for the
  168. :func:`~django.conf.urls.include` functions don't have a ``$`` (end-of-string
  169. match character) but rather a trailing slash. Whenever Django encounters
  170. :func:`~django.conf.urls.include`, it chops off whatever part of the URL
  171. matched up to that point and sends the remaining string to the included
  172. URLconf for further processing.
  173. The idea behind :func:`~django.conf.urls.include` is to make it easy to
  174. plug-and-play URLs. Since polls are in their own URLconf
  175. (``polls/urls.py``), they can be placed under "/polls/", or under
  176. "/fun_polls/", or under "/content/polls/", or any other path root, and the
  177. app will still work.
  178. Here's what happens if a user goes to "/polls/34/" in this system:
  179. * Django will find the match at ``'^polls/'``
  180. * Then, Django will strip off the matching text (``"polls/"``) and send the
  181. remaining text -- ``"34/"`` -- to the 'polls.urls' URLconf for
  182. further processing which matches ``r'^(?P<question_id>\d+)/$'`` resulting in a
  183. call to the ``detail()`` view like so::
  184. detail(request=<HttpRequest object>, question_id='34')
  185. The ``question_id='34'`` part comes from ``(?P<question_id>\d+)``. Using parentheses
  186. around a pattern "captures" the text matched by that pattern and sends it as an
  187. argument to the view function; ``?P<question_id>`` defines the name that will
  188. be used to identify the matched pattern; and ``\d+`` is a regular expression to
  189. match a sequence of digits (i.e., a number).
  190. Because the URL patterns are regular expressions, there really is no limit on
  191. what you can do with them. And there's no need to add URL cruft such as
  192. ``.html`` -- unless you want to, in which case you can do something like
  193. this::
  194. (r'^polls/latest\.html$', 'polls.views.index'),
  195. But, don't do that. It's silly.
  196. Write views that actually do something
  197. ======================================
  198. Each view is responsible for doing one of two things: returning an
  199. :class:`~django.http.HttpResponse` object containing the content for the
  200. requested page, or raising an exception such as :exc:`~django.http.Http404`. The
  201. rest is up to you.
  202. Your view can read records from a database, or not. It can use a template
  203. system such as Django's -- or a third-party Python template system -- or not.
  204. It can generate a PDF file, output XML, create a ZIP file on the fly, anything
  205. you want, using whatever Python libraries you want.
  206. All Django wants is that :class:`~django.http.HttpResponse`. Or an exception.
  207. Because it's convenient, let's use Django's own database API, which we covered
  208. in :doc:`Tutorial 1 </intro/tutorial01>`. Here's one stab at the ``index()``
  209. view, which displays the latest 5 poll questions in the system, separated by
  210. commas, according to publication date:
  211. .. snippet::
  212. :filename: polls/views.py
  213. from django.http import HttpResponse
  214. from polls.models import Question
  215. def index(request):
  216. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  217. output = ', '.join([p.question_text for p in latest_question_list])
  218. return HttpResponse(output)
  219. There's a problem here, though: the page's design is hard-coded in the view. If
  220. you want to change the way the page looks, you'll have to edit this Python code.
  221. So let's use Django's template system to separate the design from Python by
  222. creating a template that the view can use.
  223. First, create a directory called ``templates`` in your ``polls`` directory.
  224. Django will look for templates in there.
  225. Django's :setting:`TEMPLATE_LOADERS` setting contains a list of callables that
  226. know how to import templates from various sources. One of the defaults is
  227. :class:`django.template.loaders.app_directories.Loader` which looks for a
  228. "templates" subdirectory in each of the :setting:`INSTALLED_APPS` - this is how
  229. Django knows to find the polls templates even though we didn't modify
  230. :setting:`TEMPLATE_DIRS`, as we did in :ref:`Tutorial 2
  231. <ref-customizing-your-projects-templates>`.
  232. .. admonition:: Organizing templates
  233. We *could* have all our templates together, in one big templates directory,
  234. and it would work perfectly well. However, this template belongs to the
  235. polls application, so unlike the admin template we created in the previous
  236. tutorial, we'll put this one in the application's template directory
  237. (``polls/templates``) rather than the project's (``templates``). We'll
  238. discuss in more detail in the :doc:`reusable apps tutorial
  239. </intro/reusable-apps>` *why* we do this.
  240. Within the ``templates`` directory you have just created, create another
  241. directory called ``polls``, and within that create a file called
  242. ``index.html``. In other words, your template should be at
  243. ``polls/templates/polls/index.html``. Because of how the ``app_directories``
  244. template loader works as described above, you can refer to this template within
  245. Django simply as ``polls/index.html``.
  246. .. admonition:: Template namespacing
  247. Now we *might* be able to get away with putting our templates directly in
  248. ``polls/templates`` (rather than creating another ``polls`` subdirectory),
  249. but it would actually be a bad idea. Django will choose the first template
  250. it finds whose name matches, and if you had a template with the same name
  251. in a *different* application, Django would be unable to distinguish between
  252. them. We need to be able to point Django at the right one, and the easiest
  253. way to ensure this is by *namespacing* them. That is, by putting those
  254. templates inside *another* directory named for the application itself.
  255. Put the following code in that template:
  256. .. snippet:: html+django
  257. :filename: polls/templates/polls/index.html
  258. {% if latest_question_list %}
  259. <ul>
  260. {% for question in latest_question_list %}
  261. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
  262. {% endfor %}
  263. </ul>
  264. {% else %}
  265. <p>No polls are available.</p>
  266. {% endif %}
  267. Now let's update our ``index`` view in ``polls/views.py`` to use the template:
  268. .. snippet::
  269. :filename: polls/views.py
  270. from django.http import HttpResponse
  271. from django.template import RequestContext, loader
  272. from polls.models import Question
  273. def index(request):
  274. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  275. template = loader.get_template('polls/index.html')
  276. context = RequestContext(request, {
  277. 'latest_question_list': latest_question_list,
  278. })
  279. return HttpResponse(template.render(context))
  280. That code loads the template called ``polls/index.html`` and passes it a
  281. context. The context is a dictionary mapping template variable names to Python
  282. objects.
  283. Load the page by pointing your browser at "/polls/", and you should see a
  284. bulleted-list containing the "What's up" question from Tutorial 1. The link points
  285. to the question's detail page.
  286. A shortcut: :func:`~django.shortcuts.render`
  287. --------------------------------------------
  288. It's a very common idiom to load a template, fill a context and return an
  289. :class:`~django.http.HttpResponse` object with the result of the rendered
  290. template. Django provides a shortcut. Here's the full ``index()`` view,
  291. rewritten:
  292. .. snippet::
  293. :filename: polls/views.py
  294. from django.shortcuts import render
  295. from polls.models import Question
  296. def index(request):
  297. latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
  298. context = {'latest_question_list': latest_question_list}
  299. return render(request, 'polls/index.html', context)
  300. Note that once we've done this in all these views, we no longer need to import
  301. :mod:`~django.template.loader`, :class:`~django.template.RequestContext` and
  302. :class:`~django.http.HttpResponse` (you'll want to keep ``HttpResponse`` if you
  303. still have the stub methods for ``detail``, ``results``, and ``vote``).
  304. The :func:`~django.shortcuts.render` function takes the request object as its
  305. first argument, a template name as its second argument and a dictionary as its
  306. optional third argument. It returns an :class:`~django.http.HttpResponse`
  307. object of the given template rendered with the given context.
  308. Raising a 404 error
  309. ===================
  310. Now, let's tackle the question detail view -- the page that displays the question text
  311. for a given poll. Here's the view:
  312. .. snippet::
  313. :filename: polls/views.py
  314. from django.http import Http404
  315. from django.shortcuts import render
  316. from polls.models import Question
  317. # ...
  318. def detail(request, question_id):
  319. try:
  320. question = Question.objects.get(pk=question_id)
  321. except Question.DoesNotExist:
  322. raise Http404
  323. return render(request, 'polls/detail.html', {'question': question})
  324. The new concept here: The view raises the :exc:`~django.http.Http404` exception
  325. if a question with the requested ID doesn't exist.
  326. We'll discuss what you could put in that ``polls/detail.html`` template a bit
  327. later, but if you'd like to quickly get the above example working, a file
  328. containing just:
  329. .. snippet:: html+django
  330. :filename: polls/templates/polls/detail.html
  331. {{ question }}
  332. will get you started for now.
  333. A shortcut: :func:`~django.shortcuts.get_object_or_404`
  334. -------------------------------------------------------
  335. It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get`
  336. and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
  337. provides a shortcut. Here's the ``detail()`` view, rewritten:
  338. .. snippet::
  339. :filename: polls/views.py
  340. from django.shortcuts import render, get_object_or_404
  341. from polls.models import Question
  342. # ...
  343. def detail(request, question_id):
  344. question = get_object_or_404(Question, pk=question_id)
  345. return render(request, 'polls/detail.html', {'question': question})
  346. The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
  347. as its first argument and an arbitrary number of keyword arguments, which it
  348. passes to the :meth:`~django.db.models.query.QuerySet.get` function of the
  349. model's manager. It raises :exc:`~django.http.Http404` if the object doesn't
  350. exist.
  351. .. admonition:: Philosophy
  352. Why do we use a helper function :func:`~django.shortcuts.get_object_or_404`
  353. instead of automatically catching the
  354. :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher
  355. level, or having the model API raise :exc:`~django.http.Http404` instead of
  356. :exc:`~django.core.exceptions.ObjectDoesNotExist`?
  357. Because that would couple the model layer to the view layer. One of the
  358. foremost design goals of Django is to maintain loose coupling. Some
  359. controlled coupling is introduced in the :mod:`django.shortcuts` module.
  360. There's also a :func:`~django.shortcuts.get_list_or_404` function, which works
  361. just as :func:`~django.shortcuts.get_object_or_404` -- except using
  362. :meth:`~django.db.models.query.QuerySet.filter` instead of
  363. :meth:`~django.db.models.query.QuerySet.get`. It raises
  364. :exc:`~django.http.Http404` if the list is empty.
  365. Use the template system
  366. =======================
  367. Back to the ``detail()`` view for our poll application. Given the context
  368. variable ``question``, here's what the ``polls/detail.html`` template might look
  369. like:
  370. .. snippet:: html+django
  371. :filename: polls/templates/polls/detail.html
  372. <h1>{{ question.question_text }}</h1>
  373. <ul>
  374. {% for choice in question.choice_set.all %}
  375. <li>{{ choice.choice_text }}</li>
  376. {% endfor %}
  377. </ul>
  378. The template system uses dot-lookup syntax to access variable attributes. In
  379. the example of ``{{ question.question_text }}``, first Django does a dictionary lookup
  380. on the object ``question``. Failing that, it tries an attribute lookup -- which
  381. works, in this case. If attribute lookup had failed, it would've tried a
  382. list-index lookup.
  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. See the :doc:`template guide </topics/templates>` for more about templates.
  388. Removing hardcoded URLs in templates
  389. ====================================
  390. Remember, when we wrote the link to a question in the ``polls/index.html``
  391. template, the link was partially hardcoded like this:
  392. .. code-block:: html+django
  393. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
  394. The problem with this hardcoded, tightly-coupled approach is that it becomes
  395. challenging to change URLs on projects with a lot of templates. However, since
  396. you defined the name argument in the :func:`~django.conf.urls.url` functions in
  397. the ``polls.urls`` module, you can remove a reliance on specific URL paths
  398. defined in your url configurations by using the ``{% url %}`` template tag:
  399. .. code-block:: html+django
  400. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
  401. .. note::
  402. If ``{% url 'detail' question.id %}`` (with quotes) doesn't work, but
  403. ``{% url detail question.id %}`` (without quotes) does, that means you're
  404. using a version of Django < 1.5. In this case, add the following
  405. declaration at the top of your template:
  406. .. code-block:: html+django
  407. {% load url from future %}
  408. The way this works is by looking up the URL definition as specified in the
  409. ``polls.urls`` module. You can see exactly where the URL name of 'detail' is
  410. defined below::
  411. ...
  412. # the 'name' value as called by the {% url %} template tag
  413. url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'),
  414. ...
  415. If you want to change the URL of the polls detail view to something else,
  416. perhaps to something like ``polls/specifics/12/`` instead of doing it in the
  417. template (or templates) you would change it in ``polls/urls.py``::
  418. ...
  419. # added the word 'specifics'
  420. url(r'^specifics/(?P<question_id>\d+)/$', views.detail, name='detail'),
  421. ...
  422. Namespacing URL names
  423. ======================
  424. The tutorial project has just one app, ``polls``. In real Django projects,
  425. there might be five, ten, twenty apps or more. How does Django differentiate
  426. the URL names between them? For example, the ``polls`` app has a ``detail``
  427. view, and so might an app on the same project that is for a blog. How does one
  428. make it so that Django knows which app view to create for a url when using the
  429. ``{% url %}`` template tag?
  430. The answer is to add namespaces to your root URLconf. In the ``mysite/urls.py``
  431. file (the project's ``urls.py``, not the application's), go ahead and change
  432. it to include namespacing:
  433. .. snippet::
  434. :filename: mysite/urls.py
  435. from django.conf.urls import patterns, include, url
  436. from django.contrib import admin
  437. urlpatterns = patterns('',
  438. url(r'^polls/', include('polls.urls', namespace="polls")),
  439. url(r'^admin/', include(admin.site.urls)),
  440. )
  441. Now change your ``polls/index.html`` template from:
  442. .. snippet:: html+django
  443. :filename: polls/templates/polls/index.html
  444. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
  445. to point at the namespaced detail view:
  446. .. snippet:: html+django
  447. :filename: polls/templates/polls/index.html
  448. <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
  449. When you're comfortable with writing views, read :doc:`part 4 of this tutorial
  450. </intro/tutorial04>` to learn about simple form processing and generic views.