tutorial03.txt 21 KB

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