Add Django-1.2.1
[frozenviper.git] / Django-1.2.1 / docs / intro / tutorial02.txt
bloba7ab158faa88d6d5b06a339ff9102f27222431b9
1 .. _intro-tutorial02:
3 =====================================
4 Writing your first Django app, part 2
5 =====================================
7 This tutorial begins where :ref:`Tutorial 1 <intro-tutorial01>` left off. We're
8 continuing the Web-poll application and will focus on Django's
9 automatically-generated admin site.
11 .. admonition:: Philosophy
13     Generating admin sites for your staff or clients to add, change and delete
14     content is tedious work that doesn't require much creativity. For that
15     reason, Django entirely automates creation of admin interfaces for models.
17     Django was written in a newsroom environment, with a very clear separation
18     between "content publishers" and the "public" site. Site managers use the
19     system to add news stories, events, sports scores, etc., and that content is
20     displayed on the public site. Django solves the problem of creating a
21     unified interface for site administrators to edit content.
23     The admin isn't necessarily intended to be used by site visitors; it's for
24     site managers.
26 Activate the admin site
27 =======================
29 The Django admin site is not activated by default -- it's an opt-in thing. To
30 activate the admin site for your installation, do these three things:
32     * Add ``"django.contrib.admin"`` to your :setting:`INSTALLED_APPS` setting.
34     * Run ``python manage.py syncdb``. Since you have added a new application
35       to :setting:`INSTALLED_APPS`, the database tables need to be updated.
37     * Edit your ``mysite/urls.py`` file and uncomment the lines that reference
38       the admin -- there are three lines in total to uncomment. This file is a
39       URLconf; we'll dig into URLconfs in the next tutorial. For now, all you
40       need to know is that it maps URL roots to applications. In the end, you
41       should have a ``urls.py`` file that looks like this:
43     .. versionchanged:: 1.1
44         The method for adding admin urls has changed in Django 1.1.
46       .. parsed-literal::
48           from django.conf.urls.defaults import *
50           # Uncomment the next two lines to enable the admin:
51           **from django.contrib import admin**
52           **admin.autodiscover()**
54           urlpatterns = patterns('',
55               # Example:
56               # (r'^mysite/', include('mysite.foo.urls')),
58               # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
59               # to INSTALLED_APPS to enable admin documentation:
60               # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
62               # Uncomment the next line to enable the admin:
63               **(r'^admin/', include(admin.site.urls)),**
64           )
66       (The bold lines are the ones that needed to be uncommented.)
68 Start the development server
69 ============================
71 Let's start the development server and explore the admin site.
73 Recall from Tutorial 1 that you start the development server like so:
75 .. code-block:: bash
77     python manage.py runserver
79 Now, open a Web browser and go to "/admin/" on your local domain -- e.g.,
80 http://127.0.0.1:8000/admin/. You should see the admin's login screen:
82 .. image:: _images/admin01.png
83    :alt: Django admin login screen
85 Enter the admin site
86 ====================
88 Now, try logging in. (You created a superuser account in the first part of this
89 tutorial, remember?  If you didn't create one or forgot the password you can
90 :ref:`create another one <topics-auth-creating-superusers>`.) You should see
91 the Django admin index page:
93 .. image:: _images/admin02t.png
94    :alt: Django admin index page
96 You should see a few other types of editable content, including groups, users
97 and sites. These are core features Django ships with by default.
99 Make the poll app modifiable in the admin
100 =========================================
102 But where's our poll app? It's not displayed on the admin index page.
104 Just one thing to do: We need to tell the admin that ``Poll``
105 objects have an admin interface. To do this, create a file called
106 ``admin.py`` in your ``polls`` directory, and edit it to look like this::
108     from mysite.polls.models import Poll
109     from django.contrib import admin
111     admin.site.register(Poll)
113 You'll need to restart the development server to see your changes. Normally,
114 the server auto-reloads code every time you modify a file, but the action of
115 creating a new file doesn't trigger the auto-reloading logic.
117 Explore the free admin functionality
118 ====================================
120 Now that we've registered ``Poll``, Django knows that it should be displayed on
121 the admin index page:
123 .. image:: _images/admin03t.png
124    :alt: Django admin index page, now with polls displayed
126 Click "Polls." Now you're at the "change list" page for polls. This page
127 displays all the polls in the database and lets you choose one to change it.
128 There's the "What's up?" poll we created in the first tutorial:
130 .. image:: _images/admin04t.png
131    :alt: Polls change list page
133 Click the "What's up?" poll to edit it:
135 .. image:: _images/admin05t.png
136    :alt: Editing form for poll object
138 Things to note here:
140     * The form is automatically generated from the Poll model.
142     * The different model field types (:class:`~django.db.models.DateTimeField`,
143       :class:`~django.db.models.CharField`) correspond to the appropriate HTML
144       input widget. Each type of field knows how to display itself in the Django
145       admin.
147     * Each :class:`~django.db.models.DateTimeField` gets free JavaScript
148       shortcuts. Dates get a "Today" shortcut and calendar popup, and times get
149       a "Now" shortcut and a convenient popup that lists commonly entered times.
151 The bottom part of the page gives you a couple of options:
153     * Save -- Saves changes and returns to the change-list page for this type of
154       object.
156     * Save and continue editing -- Saves changes and reloads the admin page for
157       this object.
159     * Save and add another -- Saves changes and loads a new, blank form for this
160       type of object.
162     * Delete -- Displays a delete confirmation page.
164 Change the "Date published" by clicking the "Today" and "Now" shortcuts. Then
165 click "Save and continue editing." Then click "History" in the upper right.
166 You'll see a page listing all changes made to this object via the Django admin,
167 with the timestamp and username of the person who made the change:
169 .. image:: _images/admin06t.png
170    :alt: History page for poll object
172 Customize the admin form
173 ========================
175 Take a few minutes to marvel at all the code you didn't have to write. By
176 registering the Poll model with ``admin.site.register(Poll)``, Django was able
177 to construct a default form representation. Often, you'll want to customize how
178 the admin form looks and works. You'll do this by telling Django the options
179 you want when you register the object.
181 Let's see how this works by re-ordering the fields on the edit form. Replace
182 the ``admin.site.register(Poll)`` line with::
184     class PollAdmin(admin.ModelAdmin):
185         fields = ['pub_date', 'question']
187     admin.site.register(Poll, PollAdmin)
189 You'll follow this pattern -- create a model admin object, then pass it as the
190 second argument to ``admin.site.register()`` -- any time you need to change the
191 admin options for an object.
193 This particular change above makes the "Publication date" come before the
194 "Question" field:
196 .. image:: _images/admin07.png
197    :alt: Fields have been reordered
199 This isn't impressive with only two fields, but for admin forms with dozens
200 of fields, choosing an intuitive order is an important usability detail.
202 And speaking of forms with dozens of fields, you might want to split the form
203 up into fieldsets::
205     class PollAdmin(admin.ModelAdmin):
206         fieldsets = [
207             (None,               {'fields': ['question']}),
208             ('Date information', {'fields': ['pub_date']}),
209         ]
211     admin.site.register(Poll, PollAdmin)
213 The first element of each tuple in ``fieldsets`` is the title of the fieldset.
214 Here's what our form looks like now:
216 .. image:: _images/admin08t.png
217    :alt: Form has fieldsets now
219 You can assign arbitrary HTML classes to each fieldset. Django provides a
220 ``"collapse"`` class that displays a particular fieldset initially collapsed.
221 This is useful when you have a long form that contains a number of fields that
222 aren't commonly used::
224         class PollAdmin(admin.ModelAdmin):
225             fieldsets = [
226                 (None,               {'fields': ['question']}),
227                 ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
228             ]
230 .. image:: _images/admin09.png
231    :alt: Fieldset is initially collapsed
233 Adding related objects
234 ======================
236 OK, we have our Poll admin page. But a ``Poll`` has multiple ``Choices``, and
237 the admin page doesn't display choices.
239 Yet.
241 There are two ways to solve this problem. The first is to register ``Choice``
242 with the admin just as we did with ``Poll``. That's easy::
244     from mysite.polls.models import Choice
246     admin.site.register(Choice)
248 Now "Choices" is an available option in the Django admin. The "Add choice" form
249 looks like this:
251 .. image:: _images/admin10.png
252    :alt: Choice admin page
254 In that form, the "Poll" field is a select box containing every poll in the
255 database. Django knows that a :class:`~django.db.models.ForeignKey` should be
256 represented in the admin as a ``<select>`` box. In our case, only one poll
257 exists at this point.
259 Also note the "Add Another" link next to "Poll." Every object with a
260 ``ForeignKey`` relationship to another gets this for free. When you click "Add
261 Another," you'll get a popup window with the "Add poll" form. If you add a poll
262 in that window and click "Save," Django will save the poll to the database and
263 dynamically add it as the selected choice on the "Add choice" form you're
264 looking at.
266 But, really, this is an inefficient way of adding Choice objects to the system.
267 It'd be better if you could add a bunch of Choices directly when you create the
268 Poll object. Let's make that happen.
270 Remove the ``register()`` call for the Choice model. Then, edit the ``Poll``
271 registration code to read::
273     class ChoiceInline(admin.StackedInline):
274         model = Choice
275         extra = 3
277     class PollAdmin(admin.ModelAdmin):
278         fieldsets = [
279             (None,               {'fields': ['question']}),
280             ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
281         ]
282         inlines = [ChoiceInline]
284     admin.site.register(Poll, PollAdmin)
286 This tells Django: "Choice objects are edited on the Poll admin page. By
287 default, provide enough fields for 3 choices."
289 Load the "Add poll" page to see how that looks:
291 .. image:: _images/admin11t.png
292    :alt: Add poll page now has choices on it
294 It works like this: There are three slots for related Choices -- as specified
295 by ``extra`` -- and each time you come back to the "Change" page for an
296 already-created object, you get another three extra slots.
298 One small problem, though. It takes a lot of screen space to display all the
299 fields for entering related Choice objects. For that reason, Django offers a
300 tabular way of displaying inline related objects; you just need to change
301 the ``ChoiceInline`` declaration to read::
303     class ChoiceInline(admin.TabularInline):
304         #...
306 With that ``TabularInline`` (instead of ``StackedInline``), the
307 related objects are displayed in a more compact, table-based format:
309 .. image:: _images/admin12.png
310    :alt: Add poll page now has more compact choices
312 Customize the admin change list
313 ===============================
315 Now that the Poll admin page is looking good, let's make some tweaks to the
316 "change list" page -- the one that displays all the polls in the system.
318 Here's what it looks like at this point:
320 .. image:: _images/admin04t.png
321    :alt: Polls change list page
323 By default, Django displays the ``str()`` of each object. But sometimes it'd be
324 more helpful if we could display individual fields. To do that, use the
325 ``list_display`` admin option, which is a tuple of field names to display, as
326 columns, on the change list page for the object::
328     class PollAdmin(admin.ModelAdmin):
329         # ...
330         list_display = ('question', 'pub_date')
332 Just for good measure, let's also include the ``was_published_today`` custom
333 method from Tutorial 1::
335     class PollAdmin(admin.ModelAdmin):
336         # ...
337         list_display = ('question', 'pub_date', 'was_published_today')
339 Now the poll change list page looks like this:
341 .. image:: _images/admin13t.png
342    :alt: Polls change list page, updated
344 You can click on the column headers to sort by those values -- except in the
345 case of the ``was_published_today`` header, because sorting by the output of
346 an arbitrary method is not supported. Also note that the column header for
347 ``was_published_today`` is, by default, the name of the method (with
348 underscores replaced with spaces). But you can change that by giving that
349 method (in ``models.py``) a ``short_description`` attribute::
351     def was_published_today(self):
352         return self.pub_date.date() == datetime.date.today()
353     was_published_today.short_description = 'Published today?'
355 Let's add another improvement to the Poll change list page: Filters. Add the
356 following line to ``PollAdmin``::
358     list_filter = ['pub_date']
360 That adds a "Filter" sidebar that lets people filter the change list by the
361 ``pub_date`` field:
363 .. image:: _images/admin14t.png
364    :alt: Polls change list page, updated
366 The type of filter displayed depends on the type of field you're filtering on.
367 Because ``pub_date`` is a DateTimeField, Django knows to give the default
368 filter options for DateTimeFields: "Any date," "Today," "Past 7 days,"
369 "This month," "This year."
371 This is shaping up well. Let's add some search capability::
373     search_fields = ['question']
375 That adds a search box at the top of the change list. When somebody enters
376 search terms, Django will search the ``question`` field. You can use as many
377 fields as you'd like -- although because it uses a ``LIKE`` query behind the
378 scenes, keep it reasonable, to keep your database happy.
380 Finally, because Poll objects have dates, it'd be convenient to be able to
381 drill down by date. Add this line::
383     date_hierarchy = 'pub_date'
385 That adds hierarchical navigation, by date, to the top of the change list page.
386 At top level, it displays all available years. Then it drills down to months
387 and, ultimately, days.
389 Now's also a good time to note that change lists give you free pagination. The
390 default is to display 50 items per page. Change-list pagination, search boxes,
391 filters, date-hierarchies and column-header-ordering all work together like you
392 think they should.
394 Customize the admin look and feel
395 =================================
397 Clearly, having "Django administration" at the top of each admin page is
398 ridiculous. It's just placeholder text.
400 That's easy to change, though, using Django's template system. The Django admin
401 is powered by Django itself, and its interfaces use Django's own template
402 system.
404 Open your settings file (``mysite/settings.py``, remember) and look at the
405 :setting:`TEMPLATE_DIRS` setting. :setting:`TEMPLATE_DIRS` is a tuple of
406 filesystem directories to check when loading Django templates. It's a search
407 path.
409 By default, :setting:`TEMPLATE_DIRS` is empty. So, let's add a line to it, to
410 tell Django where our templates live::
412     TEMPLATE_DIRS = (
413         "/home/my_username/mytemplates", # Change this to your own directory.
414     )
416 Now copy the template ``admin/base_site.html`` from within the default Django
417 admin template directory in the source code of Django itself
418 (``django/contrib/admin/templates``) into an ``admin`` subdirectory of
419 whichever directory you're using in :setting:`TEMPLATE_DIRS`. For example, if
420 your :setting:`TEMPLATE_DIRS` includes ``"/home/my_username/mytemplates"``, as
421 above, then copy ``django/contrib/admin/templates/admin/base_site.html`` to
422 ``/home/my_username/mytemplates/admin/base_site.html``. Don't forget that
423 ``admin`` subdirectory.
425 Then, just edit the file and replace the generic Django text with your own
426 site's name as you see fit.
428 This template file contains lots of text like ``{% block branding %}``
429 and ``{{ title }}. The ``{%`` and ``{{`` tags are part of Django's
430 template language. When Django renders ``admin/base_site.html``, this
431 template language will be evaluated to produce the final HTML page.
432 Don't worry if you can't make any sense of the template right now --
433 we'll delve into Django's templating language in Tutorial 3.
435 Note that any of Django's default admin templates can be overridden. To
436 override a template, just do the same thing you did with ``base_site.html`` --
437 copy it from the default directory into your custom directory, and make
438 changes.
440 Astute readers will ask: But if :setting:`TEMPLATE_DIRS` was empty by default,
441 how was Django finding the default admin templates? The answer is that, by
442 default, Django automatically looks for a ``templates/`` subdirectory within
443 each app package, for use as a fallback. See the :ref:`template loader
444 documentation <template-loaders>` for full information.
446 Customize the admin index page
447 ==============================
449 On a similar note, you might want to customize the look and feel of the Django
450 admin index page.
452 By default, it displays all the apps in :setting:`INSTALLED_APPS` that have been
453 registered with the admin application, in alphabetical order. You may want to
454 make significant changes to the layout. After all, the index is probably the
455 most important page of the admin, and it should be easy to use.
457 The template to customize is ``admin/index.html``. (Do the same as with
458 ``admin/base_site.html`` in the previous section -- copy it from the default
459 directory to your custom template directory.) Edit the file, and you'll see it
460 uses a template variable called ``app_list``. That variable contains every
461 installed Django app. Instead of using that, you can hard-code links to
462 object-specific admin pages in whatever way you think is best. Again,
463 don't worry if you can't understand the template language -- we'll cover that
464 in more detail in Tutorial 3.
466 When you're comfortable with the admin site, read :ref:`part 3 of this tutorial
467 <intro-tutorial03>` to start working on public poll views.