tutorial03.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 Weblog
  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. Design your URLs
  29. ================
  30. The first step of writing views is to design your URL structure. You do this by
  31. creating a Python module, called a URLconf. URLconfs are how Django associates
  32. a given URL with given Python code.
  33. When a user requests a Django-powered page, the system looks at the
  34. :setting:`ROOT_URLCONF` setting, which contains a string in Python dotted
  35. syntax. Django loads that module and looks for a module-level variable called
  36. ``urlpatterns``, which is a sequence of tuples in the following format::
  37. (regular expression, Python callback function [, optional dictionary])
  38. Django starts at the first regular expression and makes its way down the list,
  39. comparing the requested URL against each regular expression until it finds one
  40. that matches.
  41. When it finds a match, Django calls the Python callback function, with an
  42. :class:`~django.http.HttpRequest` object as the first argument, any "captured"
  43. values from the regular expression as keyword arguments, and, optionally,
  44. arbitrary keyword arguments from the dictionary (an optional third item in the
  45. tuple).
  46. For more on :class:`~django.http.HttpRequest` objects, see the
  47. :doc:`/ref/request-response`. For more details on URLconfs, see the
  48. :doc:`/topics/http/urls`.
  49. When you ran ``django-admin.py startproject mysite`` at the beginning of
  50. Tutorial 1, it created a default URLconf in ``mysite/urls.py``. It also
  51. automatically set your :setting:`ROOT_URLCONF` setting (in ``settings.py``) to
  52. point at that file::
  53. ROOT_URLCONF = 'mysite.urls'
  54. Time for an example. Edit ``mysite/urls.py`` so it looks like this::
  55. from django.conf.urls import patterns, include, url
  56. from django.contrib import admin
  57. admin.autodiscover()
  58. urlpatterns = patterns('',
  59. (r'^polls/$', 'polls.views.index'),
  60. (r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),
  61. (r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'),
  62. (r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
  63. url(r'^admin/', include(admin.site.urls)),
  64. )
  65. This is worth a review. When somebody requests a page from your Web site -- say,
  66. "/polls/23/", Django will load this Python module, because it's pointed to by
  67. the :setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns``
  68. and traverses the regular expressions in order. When it finds a regular
  69. expression that matches -- ``r'^polls/(?P<poll_id>\d+)/$'`` -- it loads the
  70. function ``detail()`` from ``polls/views.py``. Finally, it calls that
  71. ``detail()`` function like so::
  72. detail(request=<HttpRequest object>, poll_id='23')
  73. The ``poll_id='23'`` part comes from ``(?P<poll_id>\d+)``. Using parentheses
  74. around a pattern "captures" the text matched by that pattern and sends it as an
  75. argument to the view function; the ``?P<poll_id>`` defines the name that will be
  76. used to identify the matched pattern; and ``\d+`` is a regular expression to
  77. match a sequence of digits (i.e., a number).
  78. Because the URL patterns are regular expressions, there really is no limit on
  79. what you can do with them. And there's no need to add URL cruft such as ``.php``
  80. -- unless you have a sick sense of humor, in which case you can do something
  81. like this::
  82. (r'^polls/latest\.php$', 'polls.views.index'),
  83. But, don't do that. It's silly.
  84. Note that these regular expressions do not search GET and POST parameters, or
  85. the domain name. For example, in a request to ``http://www.example.com/myapp/``,
  86. the URLconf will look for ``myapp/``. In a request to
  87. ``http://www.example.com/myapp/?page=3``, the URLconf will look for ``myapp/``.
  88. If you need help with regular expressions, see `Wikipedia's entry`_ and the
  89. documentation of the :mod:`re` module. Also, the O'Reilly book "Mastering
  90. Regular Expressions" by Jeffrey Friedl is fantastic.
  91. Finally, a performance note: these regular expressions are compiled the first
  92. time the URLconf module is loaded. They're super fast.
  93. .. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression
  94. Write your first view
  95. =====================
  96. Well, we haven't created any views yet -- we just have the URLconf. But let's
  97. make sure Django is following the URLconf properly.
  98. Fire up the Django development Web server:
  99. .. code-block:: bash
  100. python manage.py runserver
  101. Now go to "http://localhost:8000/polls/" on your domain in your Web browser.
  102. You should get a pleasantly-colored error page with the following message::
  103. ViewDoesNotExist at /polls/
  104. Tried index in module polls.views. Error was: 'module'
  105. object has no attribute 'index'
  106. This error happened because you haven't written a function ``index()`` in the
  107. module ``polls/views.py``.
  108. Try "/polls/23/", "/polls/23/results/" and "/polls/23/vote/". The error
  109. messages tell you which view Django tried (and failed to find, because you
  110. haven't written any views yet).
  111. Time to write the first view. Open the file ``polls/views.py``
  112. and put the following Python code in it::
  113. from django.http import HttpResponse
  114. def index(request):
  115. return HttpResponse("Hello, world. You're at the poll index.")
  116. This is the simplest view possible. Go to "/polls/" in your browser, and you
  117. should see your text.
  118. Now lets add a few more views. These views are slightly different, because
  119. they take an argument (which, remember, is passed in from whatever was
  120. captured by the regular expression in the URLconf)::
  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. Take a look in your browser, at "/polls/34/". It'll run the `detail()` method
  128. and display whatever ID you provide in the URL. Try "/polls/34/results/" and
  129. "/polls/34/vote/" too -- these will display the placeholder results and voting
  130. pages.
  131. Write views that actually do something
  132. ======================================
  133. Each view is responsible for doing one of two things: Returning an
  134. :class:`~django.http.HttpResponse` object containing the content for the
  135. requested page, or raising an exception such as :exc:`~django.http.Http404`. The
  136. rest is up to you.
  137. Your view can read records from a database, or not. It can use a template
  138. system such as Django's -- or a third-party Python template system -- or not.
  139. It can generate a PDF file, output XML, create a ZIP file on the fly, anything
  140. you want, using whatever Python libraries you want.
  141. All Django wants is that :class:`~django.http.HttpResponse`. Or an exception.
  142. Because it's convenient, let's use Django's own database API, which we covered
  143. in :doc:`Tutorial 1 </intro/tutorial01>`. Here's one stab at the ``index()``
  144. view, which displays the latest 5 poll questions in the system, separated by
  145. commas, according to publication date::
  146. from polls.models import Poll
  147. from django.http import HttpResponse
  148. def index(request):
  149. latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
  150. output = ', '.join([p.question for p in latest_poll_list])
  151. return HttpResponse(output)
  152. There's a problem here, though: The page's design is hard-coded in the view. If
  153. you want to change the way the page looks, you'll have to edit this Python code.
  154. So let's use Django's template system to separate the design from Python::
  155. from django.template import Context, loader
  156. from polls.models import Poll
  157. from django.http import HttpResponse
  158. def index(request):
  159. latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
  160. t = loader.get_template('polls/index.html')
  161. c = Context({
  162. 'latest_poll_list': latest_poll_list,
  163. })
  164. return HttpResponse(t.render(c))
  165. That code loads the template called "polls/index.html" and passes it a context.
  166. The context is a dictionary mapping template variable names to Python objects.
  167. Reload the page. Now you'll see an error::
  168. TemplateDoesNotExist at /polls/
  169. polls/index.html
  170. Ah. There's no template yet. First, create a directory, somewhere on your
  171. filesystem, whose contents Django can access. (Django runs as whatever user your
  172. server runs.) Don't put them under your document root, though. You probably
  173. shouldn't make them public, just for security's sake.
  174. Then edit :setting:`TEMPLATE_DIRS` in your ``settings.py`` to tell Django where
  175. it can find templates -- just as you did in the "Customize the admin look and
  176. feel" section of Tutorial 2.
  177. When you've done that, create a directory ``polls`` in your template directory.
  178. Within that, create a file called ``index.html``. Note that our
  179. ``loader.get_template('polls/index.html')`` code from above maps to
  180. "[template_directory]/polls/index.html" on the filesystem.
  181. Put the following code in that template:
  182. .. code-block:: html+django
  183. {% if latest_poll_list %}
  184. <ul>
  185. {% for poll in latest_poll_list %}
  186. <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
  187. {% endfor %}
  188. </ul>
  189. {% else %}
  190. <p>No polls are available.</p>
  191. {% endif %}
  192. Load the page in your Web browser, and you should see a bulleted-list
  193. containing the "What's up" poll from Tutorial 1. The link points to the poll's
  194. detail page.
  195. A shortcut: render_to_response()
  196. --------------------------------
  197. It's a very common idiom to load a template, fill a context and return an
  198. :class:`~django.http.HttpResponse` object with the result of the rendered
  199. template. Django provides a shortcut. Here's the full ``index()`` view,
  200. rewritten::
  201. from django.shortcuts import render_to_response
  202. from polls.models import Poll
  203. def index(request):
  204. latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
  205. return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
  206. Note that once we've done this in all these views, we no longer need to import
  207. :mod:`~django.template.loader`, :class:`~django.template.Context` and
  208. :class:`~django.http.HttpResponse`.
  209. The :func:`~django.shortcuts.render_to_response` function takes a template name
  210. as its first argument and a dictionary as its optional second argument. It
  211. returns an :class:`~django.http.HttpResponse` object of the given template
  212. rendered with the given context.
  213. Raising 404
  214. ===========
  215. Now, let's tackle the poll detail view -- the page that displays the question
  216. for a given poll. Here's the view::
  217. from django.http import Http404
  218. # ...
  219. def detail(request, poll_id):
  220. try:
  221. p = Poll.objects.get(pk=poll_id)
  222. except Poll.DoesNotExist:
  223. raise Http404
  224. return render_to_response('polls/detail.html', {'poll': p})
  225. The new concept here: The view raises the :exc:`~django.http.Http404` exception
  226. if a poll with the requested ID doesn't exist.
  227. We'll discuss what you could put in that ``polls/detail.html`` template a bit
  228. later, but if you'd like to quickly get the above example working, just::
  229. {{ poll }}
  230. will get you started for now.
  231. A shortcut: get_object_or_404()
  232. -------------------------------
  233. It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get`
  234. and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
  235. provides a shortcut. Here's the ``detail()`` view, rewritten::
  236. from django.shortcuts import render_to_response, get_object_or_404
  237. # ...
  238. def detail(request, poll_id):
  239. p = get_object_or_404(Poll, pk=poll_id)
  240. return render_to_response('polls/detail.html', {'poll': p})
  241. The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
  242. as its first argument and an arbitrary number of keyword arguments, which it
  243. passes to the module's :meth:`~django.db.models.query.QuerySet.get` function.
  244. It raises :exc:`~django.http.Http404` if the object doesn't exist.
  245. .. admonition:: Philosophy
  246. Why do we use a helper function :func:`~django.shortcuts.get_object_or_404`
  247. instead of automatically catching the
  248. :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher
  249. level, or having the model API raise :exc:`~django.http.Http404` instead of
  250. :exc:`~django.core.exceptions.ObjectDoesNotExist`?
  251. Because that would couple the model layer to the view layer. One of the
  252. foremost design goals of Django is to maintain loose coupling.
  253. There's also a :func:`~django.shortcuts.get_list_or_404` function, which works
  254. just as :func:`~django.shortcuts.get_object_or_404` -- except using
  255. :meth:`~django.db.models.query.QuerySet.filter` instead of
  256. :meth:`~django.db.models.query.QuerySet.get`. It raises
  257. :exc:`~django.http.Http404` if the list is empty.
  258. Write a 404 (page not found) view
  259. =================================
  260. When you raise :exc:`~django.http.Http404` from within a view, Django
  261. will load a special view devoted to handling 404 errors. It finds it
  262. by looking for the variable ``handler404`` in your root URLconf (and
  263. only in your root URLconf; setting ``handler404`` anywhere else will
  264. have no effect), which is a string in Python dotted syntax -- the same
  265. format the normal URLconf callbacks use. A 404 view itself has nothing
  266. special: It's just a normal view.
  267. You normally won't have to bother with writing 404 views. By default, URLconfs
  268. have the following line up top::
  269. from django.conf.urls import patterns, include, url
  270. That takes care of setting ``handler404`` in the current module. As you can see
  271. in ``django/conf/urls/defaults.py``, ``handler404`` is set to
  272. :func:`django.views.defaults.page_not_found` by default.
  273. Four more things to note about 404 views:
  274. * If :setting:`DEBUG` is set to ``True`` (in your settings module) then your
  275. 404 view will never be used (and thus the ``404.html`` template will never
  276. be rendered) because the traceback will be displayed instead.
  277. * The 404 view is also called if Django doesn't find a match after checking
  278. every regular expression in the URLconf.
  279. * If you don't define your own 404 view -- and simply use the default, which
  280. is recommended -- you still have one obligation: To create a ``404.html``
  281. template in the root of your template directory. The default 404 view will
  282. use that template for all 404 errors.
  283. * If :setting:`DEBUG` is set to ``False`` (in your settings module) and if
  284. you didn't create a ``404.html`` file, an ``Http500`` is raised instead.
  285. So remember to create a ``404.html``.
  286. Write a 500 (server error) view
  287. ===============================
  288. Similarly, your root URLconf may define a ``handler500``, which points
  289. to a view to call in case of server errors. Server errors happen when
  290. you have runtime errors in view code.
  291. Use the template system
  292. =======================
  293. Back to the ``detail()`` view for our poll application. Given the context
  294. variable ``poll``, here's what the "polls/detail.html" template might look
  295. like:
  296. .. code-block:: html+django
  297. <h1>{{ poll.question }}</h1>
  298. <ul>
  299. {% for choice in poll.choice_set.all %}
  300. <li>{{ choice.choice }}</li>
  301. {% endfor %}
  302. </ul>
  303. The template system uses dot-lookup syntax to access variable attributes. In
  304. the example of ``{{ poll.question }}``, first Django does a dictionary lookup
  305. on the object ``poll``. Failing that, it tries an attribute lookup -- which
  306. works, in this case. If attribute lookup had failed, it would've tried a
  307. list-index lookup.
  308. Method-calling happens in the ``{% for %}`` loop: ``poll.choice_set.all`` is
  309. interpreted as the Python code ``poll.choice_set.all()``, which returns an
  310. iterable of Choice objects and is suitable for use in the ``{% for %}`` tag.
  311. See the :doc:`template guide </topics/templates>` for more about templates.
  312. Simplifying the URLconfs
  313. ========================
  314. Take some time to play around with the views and template system. As you edit
  315. the URLconf, you may notice there's a fair bit of redundancy in it::
  316. urlpatterns = patterns('',
  317. (r'^polls/$', 'polls.views.index'),
  318. (r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),
  319. (r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'),
  320. (r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
  321. )
  322. Namely, ``polls.views`` is in every callback.
  323. Because this is a common case, the URLconf framework provides a shortcut for
  324. common prefixes. You can factor out the common prefixes and add them as the
  325. first argument to :func:`~django.conf.urls.patterns`, like so::
  326. urlpatterns = patterns('polls.views',
  327. (r'^polls/$', 'index'),
  328. (r'^polls/(?P<poll_id>\d+)/$', 'detail'),
  329. (r'^polls/(?P<poll_id>\d+)/results/$', 'results'),
  330. (r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'),
  331. )
  332. This is functionally identical to the previous formatting. It's just a bit
  333. tidier.
  334. Since you generally don't want the prefix for one app to be applied to every
  335. callback in your URLconf, you can concatenate multiple
  336. :func:`~django.conf.urls.patterns`. Your full ``mysite/urls.py`` might
  337. now look like this::
  338. from django.conf.urls import patterns, include, url
  339. from django.contrib import admin
  340. admin.autodiscover()
  341. urlpatterns = patterns('polls.views',
  342. (r'^polls/$', 'index'),
  343. (r'^polls/(?P<poll_id>\d+)/$', 'detail'),
  344. (r'^polls/(?P<poll_id>\d+)/results/$', 'results'),
  345. (r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'),
  346. )
  347. urlpatterns += patterns('',
  348. url(r'^admin/', include(admin.site.urls)),
  349. )
  350. Decoupling the URLconfs
  351. =======================
  352. While we're at it, we should take the time to decouple our poll-app URLs from
  353. our Django project configuration. Django apps are meant to be pluggable -- that
  354. is, each particular app should be transferable to another Django installation
  355. with minimal fuss.
  356. Our poll app is pretty decoupled at this point, thanks to the strict directory
  357. structure that ``python manage.py startapp`` created, but one part of it is
  358. coupled to the Django settings: The URLconf.
  359. We've been editing the URLs in ``mysite/urls.py``, but the URL design of an
  360. app is specific to the app, not to the Django installation -- so let's move the
  361. URLs within the app directory.
  362. Copy the file ``mysite/urls.py`` to ``polls/urls.py``. Then, change
  363. ``mysite/urls.py`` to remove the poll-specific URLs and insert an
  364. :func:`~django.conf.urls.include`, leaving you with::
  365. # This also imports the include function
  366. from django.conf.urls import patterns, include, url
  367. from django.contrib import admin
  368. admin.autodiscover()
  369. urlpatterns = patterns('',
  370. (r'^polls/', include('polls.urls')),
  371. url(r'^admin/', include(admin.site.urls)),
  372. )
  373. :func:`~django.conf.urls.include` simply references another URLconf.
  374. Note that the regular expression doesn't have a ``$`` (end-of-string match
  375. character) but has the trailing slash. Whenever Django encounters
  376. :func:`~django.conf.urls.include`, it chops off whatever part of the
  377. URL matched up to that point and sends the remaining string to the included
  378. URLconf for further processing.
  379. Here's what happens if a user goes to "/polls/34/" in this system:
  380. * Django will find the match at ``'^polls/'``
  381. * Then, Django will strip off the matching text (``"polls/"``) and send the
  382. remaining text -- ``"34/"`` -- to the 'polls.urls' URLconf for
  383. further processing.
  384. Now that we've decoupled that, we need to decouple the ``polls.urls``
  385. URLconf by removing the leading "polls/" from each line, and removing the
  386. lines registering the admin site. Your ``polls/urls.py`` file should now look like
  387. this::
  388. from django.conf.urls import patterns, include, url
  389. urlpatterns = patterns('polls.views',
  390. (r'^$', 'index'),
  391. (r'^(?P<poll_id>\d+)/$', 'detail'),
  392. (r'^(?P<poll_id>\d+)/results/$', 'results'),
  393. (r'^(?P<poll_id>\d+)/vote/$', 'vote'),
  394. )
  395. The idea behind :func:`~django.conf.urls.include` and URLconf
  396. decoupling is to make it easy to plug-and-play URLs. Now that polls are in their
  397. own URLconf, they can be placed under "/polls/", or under "/fun_polls/", or
  398. under "/content/polls/", or any other path root, and the app will still work.
  399. All the poll app cares about is its relative path, not its absolute path.
  400. When you're comfortable with writing views, read :doc:`part 4 of this tutorial
  401. </intro/tutorial04>` to learn about simple form processing and generic views.