tutorial03.txt 22 KB

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