Django

Code

root/django/branches/0.90-bugfixes/docs/tutorial02.txt

Revision 1262, 18.4 kB (checked in by adrian, 3 years ago)

Changed tutorial02 not to say redirects and flatpages are included

Line 
1 =====================================
2 Writing your first Django app, part 2
3 =====================================
4
5 By Adrian Holovaty <holovaty@gmail.com>
6
7 This tutorial begins where `Tutorial 1`_ left off. We're continuing the Web-poll
8 application and will focus on Django's automatically-generated admin site.
9
10 .. _Tutorial 1: http://www.djangoproject.com/documentation/tutorial1/
11
12 .. admonition:: Philosophy
13
14     Generating admin sites for your staff or clients to add, change and delete
15     content is tedious work that doesn't require much creativity. For that reason,
16     Django entirely automates creation of admin interfaces for models.
17
18     Django was written in a newsroom environment, with a very clear separation
19     between "content publishers" and the "public" site. Site managers use the
20     system to add news stories, events, sports scores, etc., and that content is
21     displayed on the public site. Django solves the problem of creating a unified
22     interface for site administrators to edit content.
23
24     The admin isn't necessarily intended to be used by site visitors; it's for site
25     managers.
26
27 Activate the admin site
28 =======================
29
30 The Django admin site is not activated by default -- it's an opt-in thing. To
31 activate the admin site for your installation, do these three things:
32
33     * Add ``"django.contrib.admin"`` to your ``INSTALLED_APPS`` setting.
34     * Run the command ``django-admin.py install admin``. This will create an
35       extra database table that the admin needs.
36     * Edit your ``myproject.urls`` file and uncomment the line below
37       "Uncomment this for admin:". This file is a URLconf; we'll dig into
38       URLconfs in the next tutorial. For now, all you need to know is that it
39       maps URL roots to applications.
40
41 Create a user account
42 =====================
43
44 Run the following command to create a superuser account for your admin site::
45
46     django-admin.py createsuperuser --settings=myproject.settings
47
48 The script will prompt you for a username, e-mail address and password (twice).
49
50 Start the development server
51 ============================
52
53 To make things easy, Django comes with a pure-Python Web server that builds on
54 the BaseHTTPServer included in Python's standard library. Let's start the
55 server and explore the admin site.
56
57 Just run the following command to start the server::
58
59     django-admin.py runserver --settings=myproject.settings
60
61 It'll start a Web server running locally -- on port 8000, by default. If you
62 want to change the server's port, pass it as a command-line argument::
63
64     django-admin.py runserver 8080 --settings=myproject.settings
65
66 DON'T use this server in anything resembling a production environment. It's
67 intended only for use while developing.
68
69 Now, open a Web browser and go to "/admin/" on your local domain -- e.g.,
70 http://127.0.0.1:8000/admin/. You should see the admin's login screen:
71
72 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin01.png
73    :alt: Django admin login screen
74
75 Enter the admin site
76 ====================
77
78 Now, try logging in. You should see the Django admin index page:
79
80 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin02t.png
81    :alt: Django admin index page
82    :target: http://media.djangoproject.com/img/doc/tutorial/admin02.png
83
84 By default, you should see two types of editable content: groups and users.
85 These are core features Django ships with by default.
86
87 .. _"I can't log in" questions: http://www.djangoproject.com/documentation/faq/#the-admin-site
88
89 Make the poll app modifiable in the admin
90 =========================================
91
92 But where's our poll app? It's not displayed on the admin index page.
93
94 Just one thing to do: We need to specify in the ``polls.Poll`` model that Poll
95 objects have an admin interface. Edit the ``myproject/apps/polls/models/polls.py``
96 file and make the following change to add an inner ``META`` class with an
97 ``admin`` attribute::
98
99     class Poll(meta.Model):
100         # ...
101         class META:
102             admin = meta.Admin()
103
104 The ``class META`` contains all non-field metadata about this model.
105
106 Now reload the Django admin page to see your changes. Note that you don't have
107 to restart the development server -- it auto-reloads code.
108
109 Explore the free admin functionality
110 ====================================
111
112 Now that ``Poll`` has the ``admin`` attribute, Django knows that it should be
113 displayed on the admin index page:
114
115 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin03t.png
116    :alt: Django admin index page, now with polls displayed
117    :target: http://media.djangoproject.com/img/doc/tutorial/admin03.png
118
119 Click "Polls." Now you're at the "change list" page for polls. This page
120 displays all the polls in the database and lets you choose one to change it.
121 There's the "What's up?" poll we created in the first tutorial:
122
123 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin04t.png
124    :alt: Polls change list page
125    :target: http://media.djangoproject.com/img/doc/tutorial/admin04.png
126
127 Click the "What's up?" poll to edit it:
128
129 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin05t.png
130    :alt: Editing form for poll object
131    :target: http://media.djangoproject.com/img/doc/tutorial/admin05.png
132
133 Things to note here:
134
135 * The form is automatically generated from the Poll model.
136 * The different model field types (``meta.DateTimeField``, ``meta.CharField``)
137   correspond to the appropriate HTML input widget. Each type of field knows
138   how to display itself in the Django admin.
139 * Each ``DateTimeField`` gets free JavaScript shortcuts. Dates get a "Today"
140   shortcut and calendar popup, and times get a "Now" shortcut and a convenient
141   popup that lists commonly entered times.
142
143 The bottom part of the page gives you a couple of options:
144
145 * Save -- Saves changes and returns to the change-list page for this type of
146   object.
147 * Save and continue editing -- Saves changes and reloads the admin page for
148   this object.
149 * Save and add another -- Saves changes and loads a new, blank form for this
150   type of object.
151 * Delete -- Displays a delete confirmation page.
152
153 Change the "Date published" by clicking the "Today" and "Now" shortcuts. Then
154 click "Save and continue editing." Then click "History" in the upper right.
155 You'll see a page listing all changes made to this object via the Django admin,
156 with the timestamp and username of the person who made the change:
157
158 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin06t.png
159    :alt: History page for poll object
160    :target: http://media.djangoproject.com/img/doc/tutorial/admin06.png
161
162 Customize the admin form
163 ========================
164
165 Take a few minutes to marvel at all the code you didn't have to write.
166
167 Let's customize this a bit. We can reorder the fields by explicitly adding a
168 ``fields`` parameter to ``meta.Admin``::
169
170         admin = meta.Admin(
171             fields = (
172                 (None, {'fields': ('pub_date', 'question')}),
173             ),
174         )
175
176 That made the "Publication date" show up first instead of second:
177
178 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin07.png
179    :alt: Fields have been reordered
180
181 This isn't impressive with only two fields, but for admin forms with dozens
182 of fields, choosing an intuitive order is an important usability detail.
183
184 And speaking of forms with dozens of fields, you might want to split the form
185 up into fieldsets::
186
187         admin = meta.Admin(
188             fields = (
189                 (None, {'fields': ('question',)}),
190                 ('Date information', {'fields': ('pub_date',)}),
191             ),
192         )
193
194 The first element of each tuple in ``fields`` is the title of the fieldset.
195 Here's what our form looks like now:
196
197 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin08t.png
198    :alt: Form has fieldsets now
199    :target: http://media.djangoproject.com/img/doc/tutorial/admin08.png
200
201 You can assign arbitrary HTML classes to each fieldset. Django provides a
202 ``"collapse"`` class that displays a particular fieldset initially collapsed.
203 This is useful when you have a long form that contains a number of fields that
204 aren't commonly used::
205
206         admin = meta.Admin(
207             fields = (
208                 (None, {'fields': ('question',)}),
209                 ('Date information', {'fields': ('pub_date',), 'classes': 'collapse'}),
210             ),
211         )
212
213 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin09.png
214    :alt: Fieldset is initially collapsed
215
216 Adding related objects
217 ======================
218
219 OK, we have our Poll admin page. But a ``Poll`` has multiple ``Choices``, and the admin
220 page doesn't display choices.
221
222 Yet.
223
224 In this case, there are two ways to solve this problem. The first is to give
225 the ``Choice`` model its own ``admin`` attribute, just as we did with ``Poll``.
226 Here's what that would look like::
227
228     class Choice(meta.Model):
229         # ...
230         class META:
231             admin = meta.Admin()
232
233 Now "Choices" is an available option in the Django admin. The "Add choice" form
234 looks like this:
235
236 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin10.png
237    :alt: Choice admin page
238
239 In that form, the "Poll" field is a select box containing every poll in the
240 database. In our case, only one poll exists at this point.
241
242 Also note the "Add Another" link next to "Poll." Every object with a ForeignKey
243 relationship to another gets this for free. When you click "Add Another," you'll
244 get a popup window with the "Add poll" form. If you add a poll in that window
245 and click "Save," Django will save the poll to the database and dynamically add
246 it as the selected choice on the "Add choice" form you're looking at.
247
248 But, really, this is an inefficient way of adding Choice objects to the system.
249 It'd be better if you could add a bunch of Choices directly when you create the
250 Poll object. Let's make that happen.
251
252 Remove the ``admin`` for the Choice model. Then, edit the ``ForeignKey(Poll)``
253 field like so::
254
255     poll = meta.ForeignKey(Poll, edit_inline=meta.STACKED, num_in_admin=3)
256
257 This tells Django: "Choice objects are edited on the Poll admin page. By
258 default, provide enough fields for 3 Choices."
259
260 Then change the other fields in ``Choice`` to give them ``core=True``::
261
262     choice = meta.CharField(maxlength=200, core=True)
263     votes = meta.IntegerField(core=True)
264
265 This tells Django: "When you edit a Choice on the Poll admin page, the 'choice'
266 and 'votes' fields are required. The presence of at least one of them signifies
267 the addition of a new Choice object, and clearing both of them signifies the
268 deletion of that existing Choice object."
269
270 Load the "Add poll" page to see how that looks:
271
272 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin11t.png
273    :alt: Add poll page now has choices on it
274    :target: http://media.djangoproject.com/img/doc/tutorial/admin11.png
275
276 It works like this: There are three slots for related Choices -- as specified
277 by ``num_in_admin`` -- but each time you come back to the "Change" page for an
278 already-created object, you get one extra slot. (This means there's no
279 hard-coded limit on how many related objects can be added.) If you wanted space
280 for three extra Choices each time you changed the poll, you'd use
281 ``num_extra_on_change=3``.
282
283 One small problem, though. It takes a lot of screen space to display all the
284 fields for entering related Choice objects. For that reason, Django offers an
285 alternate way of displaying inline related objects::
286
287     poll = meta.ForeignKey(Poll, edit_inline=meta.TABULAR, num_in_admin=3)
288
289 With that ``edit_inline=meta.TABULAR`` (instead of ``meta.STACKED``), the
290 related objects are displayed in a more compact, table-based format:
291
292 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin12.png
293    :alt: Add poll page now has more compact choices
294
295 Customize the admin change list
296 ===============================
297
298 Now that the Poll admin page is looking good, let's make some tweaks to the
299 "change list" page -- the one that displays all the polls in the system.
300
301 Here's what it looks like at this point:
302
303 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin04t.png
304    :alt: Polls change list page
305    :target: http://media.djangoproject.com/img/doc/tutorial/admin04.png
306
307 By default, Django displays the ``repr()`` of each object. But it'd be more
308 helpful if we could display individual fields. To do that, use the
309 ``list_display`` option, which is a tuple of field names to display, as columns,
310 on the change list page for the object::
311
312     class Poll(meta.Model):
313         # ...
314         class META:
315             admin = meta.Admin(
316                 # ...
317                 list_display = ('question', 'pub_date'),
318             )
319
320 Just for good measure, let's also include the ``was_published_today`` custom
321 method from Tutorial 1::
322
323     list_display = ('question', 'pub_date', 'was_published_today'),
324
325 Now the poll change list page looks like this:
326
327 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin13t.png
328    :alt: Polls change list page, updated
329    :target: http://media.djangoproject.com/img/doc/tutorial/admin13.png
330
331 You can click on the column headers to sort by those values -- except in the
332 case of the ``was_published_today`` header, because sorting by the output of
333 an arbitrary method is not supported. Also note that the column header for
334 ``was_published_today`` is, by default, the name of the method. But you can
335 change that by giving that method a ``short_description`` attribute::
336
337     def was_published_today(self):
338         return self.pub_date.date() == datetime.date.today()
339     was_published_today.short_description = 'Was published today'
340
341
342 Let's add another improvement to the Poll change list page: Filters. Add the
343 following line to ``Poll.admin``::
344
345     list_filter = ['pub_date'],
346
347 That adds a "Filter" sidebar that lets people filter the change list by the
348 ``pub_date`` field:
349
350 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin14t.png
351    :alt: Polls change list page, updated
352    :target: http://media.djangoproject.com/img/doc/tutorial/admin14.png
353
354 The type of filter displayed depends on the type of field you're filtering on.
355 Because ``pub_date`` is a DateTimeField, Django knows to give the default
356 filter options for DateTimeFields: "Any date," "Today," "Past 7 days,"
357 "This month," "This year."
358
359 This is shaping up well. Let's add some search capability::
360
361     search_fields = ['question'],
362
363 That adds a search box at the top of the change list. When somebody enters
364 search terms, Django will search the ``question`` field. You can use as many
365 fields as you'd like -- although because it uses a LIKE query behind the
366 scenes, keep it reasonable, to keep your database happy.
367
368 Finally, because Poll objects have dates, it'd be convenient to be able to
369 drill down by date. Add this line::
370
371     date_hierarchy = 'pub_date',
372
373 That adds hierarchical navigation, by date, to the top of the change list page.
374 At top level, it displays all available years. Then it drills down to months
375 and, ultimately, days.
376
377 Now's also a good time to note that change lists give you free pagination. The
378 default is to display 50 items per page. Change-list pagination, search boxes,
379 filters, date-hierarchies and column-header-ordering all work together like you
380 think they should.
381
382 Customize the admin look and feel
383 =================================
384
385 Clearly, having "Django administration" and "example.com" at the top of each
386 admin page is ridiculous. It's just placeholder text.
387
388 That's easy to change, though, using Django's template system. The Django admin
389 is powered by Django itself, and its interfaces use Django's own template
390 system. (How meta!)
391
392 Open your settings file (``myproject/settings.py``, remember) and look at the
393 ``TEMPLATE_DIRS`` setting. ``TEMPLATE_DIRS`` is a tuple of filesystem
394 directories to check when loading Django templates. It's a search path.
395
396 By default, ``TEMPLATE_DIRS`` is empty. So, let's add a line to it, to tell
397 Django where our templates live::
398
399     TEMPLATE_DIRS = (
400         "/home/mytemplates", # Change this to your own directory.
401     )
402
403 Now copy the template ``admin/base_site.html`` from within the default Django
404 admin template directory (``django/contrib/admin/templates``) into an ``admin``
405 subdirectory of whichever directory you're using in ``TEMPLATE_DIRS``. For
406 example, if your ``TEMPLATE_DIRS`` includes ``"/home/mytemplates"``, as above,
407 then copy ``django/contrib/admin/templates/admin/base_site.html`` to
408 ``/home/mytemplates/admin/base_site.html``.
409
410 Then, just edit the file and replace the generic Django text with your own
411 site's name and URL as you see fit.
412
413 Note that any of Django's default admin templates can be overridden. To
414 override a template, just do the same thing you did with ``base_site.html`` --
415 copy it from the default directory into your custom directory, and make
416 changes.
417
418 Astute readers will ask: But if ``TEMPLATE_DIRS`` was empty by default, how was
419 Django finding the default admin templates? The answer is that, by default,
420 Django automatically looks for a ``templates/`` subdirectory within each app
421 package, for use as a fallback. See the `loader types documentation`_ for full
422 information.
423
424 .. _loader types documentation: http://www.djangoproject.com/documentation/templates_python/#loader-types
425
426 Customize the admin index page
427 ==============================
428
429 On a similar note, you might want to customize the look and feel of the Django
430 admin index page.
431
432 By default, it displays all available apps, according to your ``INSTALLED_APPS``
433 setting. But the order in which it displays things is random, and you may want
434 to make significant changes to the layout. After all, the index is probably the
435 most important page of the admin, and it should be easy to use.
436
437 The template to customize is ``admin/index.html``. (Do the same as with
438 ``admin/base_site.html`` in the previous section -- copy it from the default
439 directory to your custom template directory.) Edit the file, and you'll see it
440 uses a template tag called ``{% get_admin_app_list as app_list %}``. That's the
441 magic that retrieves every installed Django app. Instead of using that, you can
442 hard-code links to object-specific admin pages in whatever way you think is
443 best.
444
445 Django offers another shortcut in this department. Run the command
446 ``django-admin.py adminindex polls`` to get a chunk of template code for
447 inclusion in the admin index template. It's a useful starting point.
448
449 For full details on customizing the look and feel of the Django admin site in
450 general, see the `Django admin CSS guide`_.
451
452 When you're comfortable with the admin site, read `part 3 of this tutorial`_ to
453 start working on public poll views.
454
455 .. _Django admin CSS guide: http://www.djangoproject.com/documentation/admin_css/
456 .. _part 3 of this tutorial: http://www.djangoproject.com/documentation/tutorial3/
Note: See TracBrowser for help on using the browser.