tutorial03.txt 20 KB

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