tutorial03.txt 20 KB

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