1 =====================================
2 Writing your first Django app, part 2
3 =====================================
5 By Adrian Holovaty <holovaty@gmail.com>
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.
10 .. _Tutorial 1: http://www.djangoproject.com/documentation/tutorial1/
12 .. admonition:: Philosophy
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.
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.
24 The admin isn't necessarily intended to be used by site visitors; it's for site
27 Activate the admin site
28 =======================
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:
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.py`` 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.
44 Run the following command to create a superuser account for your admin site::
46 django-admin.py createsuperuser --settings=myproject.settings
48 The script will prompt you for a username, e-mail address and password (twice).
50 Start the development server
51 ============================
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.
57 Just run the following command to start the server::
59 django-admin.py runserver --settings=myproject.settings
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::
64 django-admin.py runserver 8080 --settings=myproject.settings
66 DON'T use this server in anything resembling a production environment. It's
67 intended only for use while developing.
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:
72 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin01.png
73 :alt: Django admin login screen
78 Now, try logging in. You should see the Django admin index page:
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
84 By default, you should see two types of editable content: groups and users.
85 These are core features Django ships with by default.
87 .. _"I can't log in" questions: http://www.djangoproject.com/documentation/faq/#the-admin-site
89 Make the poll app modifiable in the admin
90 =========================================
92 But where's our poll app? It's not displayed on the admin index page.
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
99 class Poll(meta.Model):
104 The ``class META`` contains all non-field metadata about this model.
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.
109 Explore the free admin functionality
110 ====================================
112 Now that ``Poll`` has the ``admin`` attribute, Django knows that it should be
113 displayed on the admin index page:
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
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:
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
127 Click the "What's up?" poll to edit it:
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
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.
143 The bottom part of the page gives you a couple of options:
145 * Save -- Saves changes and returns to the change-list page for this type of
147 * Save and continue editing -- Saves changes and reloads the admin page for
149 * Save and add another -- Saves changes and loads a new, blank form for this
151 * Delete -- Displays a delete confirmation page.
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:
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
162 Customize the admin form
163 ========================
165 Take a few minutes to marvel at all the code you didn't have to write.
167 Let's customize this a bit. We can reorder the fields by explicitly adding a
168 ``fields`` parameter to ``meta.Admin``::
172 (None, {'fields': ('pub_date', 'question')}),
176 That made the "Publication date" show up first instead of second:
178 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin07.png
179 :alt: Fields have been reordered
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.
184 And speaking of forms with dozens of fields, you might want to split the form
189 (None, {'fields': ('question',)}),
190 ('Date information', {'fields': ('pub_date',)}),
194 The first element of each tuple in ``fields`` is the title of the fieldset.
195 Here's what our form looks like now:
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
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::
208 (None, {'fields': ('question',)}),
209 ('Date information', {'fields': ('pub_date',), 'classes': 'collapse'}),
213 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin09.png
214 :alt: Fieldset is initially collapsed
216 Adding related objects
217 ======================
219 OK, we have our Poll admin page. But a ``Poll`` has multiple ``Choices``, and the admin
220 page doesn't display choices.
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::
228 class Choice(meta.Model):
233 Now "Choices" is an available option in the Django admin. The "Add choice" form
236 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin10.png
237 :alt: Choice admin page
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.
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.
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.
252 Remove the ``admin`` for the Choice model. Then, edit the ``ForeignKey(Poll)``
255 poll = meta.ForeignKey(Poll, edit_inline=meta.STACKED, num_in_admin=3)
257 This tells Django: "Choice objects are edited on the Poll admin page. By
258 default, provide enough fields for 3 Choices."
260 Then change the other fields in ``Choice`` to give them ``core=True``::
262 choice = meta.CharField(maxlength=200, core=True)
263 votes = meta.IntegerField(core=True)
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."
270 Load the "Add poll" page to see how that looks:
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
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``.
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::
287 poll = meta.ForeignKey(Poll, edit_inline=meta.TABULAR, num_in_admin=3)
289 With that ``edit_inline=meta.TABULAR`` (instead of ``meta.STACKED``), the
290 related objects are displayed in a more compact, table-based format:
292 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin12.png
293 :alt: Add poll page now has more compact choices
295 Customize the admin change list
296 ===============================
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.
301 Here's what it looks like at this point:
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
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::
312 class Poll(meta.Model):
317 list_display = ('question', 'pub_date'),
320 Just for good measure, let's also include the ``was_published_today`` custom
321 method from Tutorial 1::
323 list_display = ('question', 'pub_date', 'was_published_today'),
325 Now the poll change list page looks like this:
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
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 (with
335 underscores replaced with spaces). But you can change that by giving that
336 method a ``short_description`` attribute::
338 def was_published_today(self):
339 return self.pub_date.date() == datetime.date.today()
340 was_published_today.short_description = 'Published today?'
343 Let's add another improvement to the Poll change list page: Filters. Add the
344 following line to ``Poll.admin``::
346 list_filter = ['pub_date'],
348 That adds a "Filter" sidebar that lets people filter the change list by the
351 .. image:: http://media.djangoproject.com/img/doc/tutorial/admin14t.png
352 :alt: Polls change list page, updated
353 :target: http://media.djangoproject.com/img/doc/tutorial/admin14.png
355 The type of filter displayed depends on the type of field you're filtering on.
356 Because ``pub_date`` is a DateTimeField, Django knows to give the default
357 filter options for DateTimeFields: "Any date," "Today," "Past 7 days,"
358 "This month," "This year."
360 This is shaping up well. Let's add some search capability::
362 search_fields = ['question'],
364 That adds a search box at the top of the change list. When somebody enters
365 search terms, Django will search the ``question`` field. You can use as many
366 fields as you'd like -- although because it uses a LIKE query behind the
367 scenes, keep it reasonable, to keep your database happy.
369 Finally, because Poll objects have dates, it'd be convenient to be able to
370 drill down by date. Add this line::
372 date_hierarchy = 'pub_date',
374 That adds hierarchical navigation, by date, to the top of the change list page.
375 At top level, it displays all available years. Then it drills down to months
376 and, ultimately, days.
378 Now's also a good time to note that change lists give you free pagination. The
379 default is to display 50 items per page. Change-list pagination, search boxes,
380 filters, date-hierarchies and column-header-ordering all work together like you
383 Customize the admin look and feel
384 =================================
386 Clearly, having "Django administration" and "example.com" at the top of each
387 admin page is ridiculous. It's just placeholder text.
389 That's easy to change, though, using Django's template system. The Django admin
390 is powered by Django itself, and its interfaces use Django's own template
393 Open your settings file (``myproject/settings.py``, remember) and look at the
394 ``TEMPLATE_DIRS`` setting. ``TEMPLATE_DIRS`` is a tuple of filesystem
395 directories to check when loading Django templates. It's a search path.
397 By default, ``TEMPLATE_DIRS`` is empty. So, let's add a line to it, to tell
398 Django where our templates live::
401 "/home/mytemplates", # Change this to your own directory.
404 Now copy the template ``admin/base_site.html`` from within the default Django
405 admin template directory (``django/contrib/admin/templates``) into an ``admin``
406 subdirectory of whichever directory you're using in ``TEMPLATE_DIRS``. For
407 example, if your ``TEMPLATE_DIRS`` includes ``"/home/mytemplates"``, as above,
408 then copy ``django/contrib/admin/templates/admin/base_site.html`` to
409 ``/home/mytemplates/admin/base_site.html``.
411 Then, just edit the file and replace the generic Django text with your own
412 site's name and URL as you see fit.
414 Note that any of Django's default admin templates can be overridden. To
415 override a template, just do the same thing you did with ``base_site.html`` --
416 copy it from the default directory into your custom directory, and make
419 Astute readers will ask: But if ``TEMPLATE_DIRS`` was empty by default, how was
420 Django finding the default admin templates? The answer is that, by default,
421 Django automatically looks for a ``templates/`` subdirectory within each app
422 package, for use as a fallback. See the `loader types documentation`_ for full
425 .. _loader types documentation: http://www.djangoproject.com/documentation/templates_python/#loader-types
427 Customize the admin index page
428 ==============================
430 On a similar note, you might want to customize the look and feel of the Django
433 By default, it displays all available apps, according to your ``INSTALLED_APPS``
434 setting. But the order in which it displays things is random, and you may want
435 to make significant changes to the layout. After all, the index is probably the
436 most important page of the admin, and it should be easy to use.
438 The template to customize is ``admin/index.html``. (Do the same as with
439 ``admin/base_site.html`` in the previous section -- copy it from the default
440 directory to your custom template directory.) Edit the file, and you'll see it
441 uses a template tag called ``{% get_admin_app_list as app_list %}``. That's the
442 magic that retrieves every installed Django app. Instead of using that, you can
443 hard-code links to object-specific admin pages in whatever way you think is
446 Django offers another shortcut in this department. Run the command
447 ``django-admin.py adminindex polls`` to get a chunk of template code for
448 inclusion in the admin index template. It's a useful starting point.
450 For full details on customizing the look and feel of the Django admin site in
451 general, see the `Django admin CSS guide`_.
453 When you're comfortable with the admin site, read `part 3 of this tutorial`_ to
454 start working on public poll views.
456 .. _Django admin CSS guide: http://www.djangoproject.com/documentation/admin_css/
457 .. _part 3 of this tutorial: http://www.djangoproject.com/documentation/tutorial3/