Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 993 lines (748 sloc) 44.513 kb
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1 ================================
2 Chapter 6: The Django Admin Site
3 ================================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
4
5 For a certain class of Web sites, an *admin interface* is an essential part of
6 the infrastructure. This is a Web-based interface, limited to trusted site
7 administrators, that enables the adding, editing and deletion of site content.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
8 Some common examples: the interface you use to post to your blog, the backend
9 site managers use to moderate user-generated comments, the tool your clients
10 use to update the press releases on the Web site you built for them.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
11
12 There's a problem with admin interfaces, though: it's boring to build them.
13 Web development is fun when you're developing public-facing functionality, but
14 building admin interfaces is always the same. You have to authenticate users,
15 display and handle forms, validate input, and so on. It's boring, and it's
16 repetitive.
17
18 So what's Django's approach to these boring, repetitive tasks? It does it all
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
19 for you -- in just a couple of lines of code, no less. With Django, building an
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
20 admin interface is a solved problem.
21
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
22 This chapter is about Django's automatic admin interface. The feature works by
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
23 reading metadata in your model to provide a powerful and production-ready
24 interface that site administrators can start using immediately. Here, we discuss
25 how to activate, use, and customize this feature.
26
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
27 Note that we recommend reading this chapter even if you don't intend to use the
28 Django admin site, because we introduce a few concepts that apply to all of
29 Django, regardless of admin-site usage.
30
31 The django.contrib packages
32 ===========================
33
34 Django's automatic admin is part of a larger suite of Django functionality
35 called ``django.contrib`` -- the part of the Django codebase that contains
36 various useful add-ons to the core framework. You can think of
37 ``django.contrib`` as Django's equivalent of the Python standard library --
38 optional, de facto implementations of common patterns. They're bundled with
39 Django so that you don't have to reinvent the wheel in your own applications.
40
41 The admin site is the first part of ``django.contrib`` that we're covering in
42 this book; technically, it's called ``django.contrib.admin``. Other available
43 features in ``django.contrib`` include a user authentication system
44 (``django.contrib.auth``), support for anonymous sessions
45 (``django.contrib.sessions``) and even a system for user comments
46 (``django.contrib.comments``). You'll get to know the various ``django.contrib``
47 features as you become a Django expert, and we'll spend some more time
48 discussing them in Chapter 16. For now, just know that Django ships with many
49 nice add-ons, and ``django.contrib`` is generally where they live.
50
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
51 Activating the Admin Interface
52 ==============================
53
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
54 The Django admin site is entirely optional, because only certain types of sites
55 need this functionality. That means you'll need to take a few steps to activate
56 it in your project.
57
58 First, make a few changes to your settings file:
59
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
60 1. Add ``'django.contrib.admin'`` to the ``INSTALLED_APPS`` setting. (The
61 order of ``INSTALLED_APPS`` doesn't matter, but we like to keep things
62 alphabetical so it's easy for a human to read.)
63
64 2. Make sure ``INSTALLED_APPS`` contains ``'django.contrib.auth'``,
d64dfe8 @bharathwaaj Update admin INSTALLED_APPS requirements to 1.4
bharathwaaj authored
65 ``'django.contrib.contenttypes'``, ``'django.contrib.messages'``
66 and ``'django.contrib.sessions'``. The
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
67 Django admin site requires these three packages. (If you're following
68 along with our ongoing ``mysite`` project, note that we commented out
d64dfe8 @bharathwaaj Update admin INSTALLED_APPS requirements to 1.4
bharathwaaj authored
69 these four ``INSTALLED_APPS`` entries in Chapter 5. Uncomment them now.)
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
70
71 3. Make sure ``MIDDLEWARE_CLASSES`` contains
72 ``'django.middleware.common.CommonMiddleware'``,
d64dfe8 @bharathwaaj Update admin INSTALLED_APPS requirements to 1.4
bharathwaaj authored
73 ``'django.contrib.messages.middleware.MessageMiddleware'``,
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
74 ``'django.contrib.sessions.middleware.SessionMiddleware'`` and
75 ``'django.contrib.auth.middleware.AuthenticationMiddleware'``. (Again,
76 if you're following along, note that we commented them out in Chapter 5,
77 so uncomment them.)
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
78
79 Second, run ``python manage.py syncdb``. This step will install the extra
80 database tables that the admin interface uses. The first time you run
81 ``syncdb`` with ``'django.contrib.auth'`` in ``INSTALLED_APPS``, you'll be
82 asked about creating a superuser. If you don't do this, you'll need to run
83 ``python manage.py createsuperuser`` separately to create an admin user
84 account; otherwise, you won't be able to log in to the admin site. (Potential
85 gotcha: the ``python manage.py createsuperuser`` command is only available if
86 ``'django.contrib.auth'`` is in your ``INSTALLED_APPS``.)
87
88 Third, add the admin site to your URLconf (in ``urls.py``, remember). By
89 default, the ``urls.py`` generated by ``django-admin.py startproject`` contains
90 commented-out code for the Django admin, and all you have to do is uncomment
91 it. For the record, here are the bits you need to make sure are in there::
92
93 # Include these import statements...
94 from django.contrib import admin
95 admin.autodiscover()
96
97 # And include this URLpattern...
98 urlpatterns = patterns('',
99 # ...
100 (r'^admin/', include(admin.site.urls)),
101 # ...
102 )
103
104 With that bit of configuration out of the way, now you can see the Django
105 admin site in action. Just run the development server
106 (``python manage.py runserver``, as in previous chapters) and visit
107 ``http://127.0.0.1:8000/admin/`` in your Web browser.
108
109 Using the Admin Site
110 ====================
111
112 The admin site is designed to be used by nontechnical users, and as such it
113 should be pretty self-explanatory. Nevertheless, we'll give you a quick
114 walkthrough of the basic features.
115
116 The first thing you'll see is a login screen, as shown in Figure 6-1.
117
118 .. figure:: graphics/chapter06/login.png
119 :alt: Screenshot of Django's login page.
120
121 Figure 6-1. Django's login screen
122
123 Log in with the username and password you set up when you added your superuser.
124 If you're unable to log in, make sure you've actually created a superuser --
125 try running ``python manage.py createsuperuser``.
126
127 Once you're logged in, the first thing you'll see will be the admin home page.
128 This page lists all the available types of data that can be edited on the admin
129 site. At this point, because we haven't activated any of our own models yet,
130 the list is sparse: it includes only Groups and Users, which are the two
131 default admin-editable models.
132
133 .. DWP The screenshot contains books etc too.
134
135 .. figure:: graphics/chapter06/admin_index.png
136 :alt: Screenshot of the Django admin home page.
137
138 Figure 6-2. The Django admin home page
139
140 Each type of data in the Django admin site has a *change list* and an
141 *edit form*. Change lists show you all the available objects in the database,
142 and edit forms let you add, change or delete particular records in your
143 database.
144
145 .. admonition:: Other languages
146
147 If your primary language is not English and your Web browser is configured
148 to prefer a language other than English, you can make a quick change to
149 see whether the Django admin site has been translated into your language.
150 Just add ``'django.middleware.locale.LocaleMiddleware'`` to your
151 ``MIDDLEWARE_CLASSES`` setting, making sure it appears *after*
152 ``'django.contrib.sessions.middleware.SessionMiddleware'``.
153
154 When you've done that, reload the admin index page. If a translation for
155 your language is available, then the various parts of the interface -- from
156 the "Change password" and "Log out" links at the top of the page, to the
157 "Groups" and "Users" links in the middle -- will appear in your language
158 instead of English. Django ships with translations for dozens of languages.
159
160 For much more on Django's internationalization features, see Chapter 19.
161
162 Click the "Change" link in the "Users" row to load the change list page for
163 users.
164
165 .. figure:: graphics/chapter06/user_changelist.png
166 :alt: Screenshot of the user change list page.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
167
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
168 Figure 6-3. The user change list page
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
169
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
170 .. DWP This screenshot is actually the list for books.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
171
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
172 This page displays all users in the database; you can think of it as a
173 prettied-up Web version of a ``SELECT * FROM auth_user;`` SQL query. If you're
174 following along with our ongoing example, you'll only see one user here,
175 assuming you've added only one, but once you have more users, you'll probably
176 find the filtering, sorting and searching options useful. Filtering options are
177 at right, sorting is available by clicking a column header, and the search box
178 at the top lets you search by username.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
179
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
180 Click the username of the user you created, and you'll see the edit form for
181 that user.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
182
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
183 .. figure:: graphics/chapter06/user_editform.png
184 :alt: Screenshot of the user edit form
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
185
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
186 Figure 6-4. The user edit form
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
187
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
188 .. DWP The edit form screenshot is for a book.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
189
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
190 This page lets you change the attributes of the user, like the
191 first/last names and various permissions. (Note that to change a user's
192 password, you should click "change password form" under the password field
193 rather than editing the hashed code.) Another thing to note here is that fields
194 of different types get different widgets -- for example, date/time fields have
195 calendar controls, boolean fields have checkboxes, character fields have simple
196 text input fields.
197
198 You can delete a record by clicking the delete button at the bottom left of its
199 edit form. That'll take you to a confirmation page, which, in some cases, will
200 display any dependent objects that will be deleted, too. (For example, if you
201 delete a publisher, any book with that publisher will be deleted, too!)
202
203 You can add a record by clicking "Add" in the appropriate column of the admin
204 home page. This will give you an empty version of the edit page, ready for you
205 to fill out.
206
207 You'll also notice that the admin interface also handles input validation for
208 you. Try leaving a required field blank or putting an invalid date into a date
209 field, and you'll see those errors when you try to save, as shown in Figure 6-5.
210
211 .. figure:: graphics/chapter06/user_editform_errors.png
212 :alt: Screenshot of an edit form displaying errors.
213
214 Figure 6-5. An edit form displaying errors
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
215
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
216 .. DWP The screenshots are still following a book example.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
217
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
218 When you edit an existing object, you'll notice a History link in the
219 upper-right corner of the window. Every change made through the admin interface
220 is logged, and you can examine this log by clicking the History link (see
221 Figure 6-6).
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
222
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
223 .. figure:: graphics/chapter06/user_history.png
224 :alt: Screenshot of an object history page.
225
226 Figure 6-6. An object history page
227
228 .. DWP Still using a book in the pictures.
229
230 Adding Your Models to the Admin Site
231 ====================================
232
233 There's one crucial part we haven't done yet. Let's add our own models to the
234 admin site, so we can add, change and delete objects in our custom database
235 tables using this nice interface. We'll continue the ``books`` example from
236 Chapter 5, where we defined three models: ``Publisher``, ``Author`` and
237 ``Book``.
238
239 Within the ``books`` directory (``mysite/books``), create a file called
240 ``admin.py``, and type in the following lines of code::
241
242 from django.contrib import admin
243 from mysite.books.models import Publisher, Author, Book
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
244
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
245 admin.site.register(Publisher)
246 admin.site.register(Author)
247 admin.site.register(Book)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
248
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
249 This code tells the Django admin site to offer an interface for each of these
250 models.
251
252 Once you've done this, go to your admin home page in your Web browser
253 (``http://127.0.0.1:8000/admin/``), and you should see a "Books" section with
254 links for Authors, Books and Publishers. (You might have to stop and start the
255 ``runserver`` for the changes to take effect.)
256
257 .. SL Tested ok
258
259 You now have a fully functional admin interface for each of those three models.
260 That was easy!
261
262 Take some time to add and change records, to populate your database with some
263 data. If you followed Chapter 5's examples of creating ``Publisher`` objects
264 (and you didn't delete them), you'll already see those records on the publisher
265 change list page.
266
267 One feature worth mentioning here is the admin site's handling of foreign keys
268 and many-to-many relationships, both of which appear in the ``Book`` model. As
269 a reminder, here's what the ``Book`` model looks like::
270
271 class Book(models.Model):
272 title = models.CharField(max_length=100)
273 authors = models.ManyToManyField(Author)
274 publisher = models.ForeignKey(Publisher)
275 publication_date = models.DateField()
276
277 def __unicode__(self):
278 return self.title
279
280 On the Django admin site's "Add book" page
281 (``http://127.0.0.1:8000/admin/books/book/add/``), the publisher (a
282 ``ForeignKey``) is represented by a select box, and the authors field
283 (a ``ManyToManyField``) is represented by a multiple-select box. Both fields
284 sit next to a green plus sign icon that lets you add related records of that
285 type. For example, if you click the green plus sign next to the "Publisher"
286 field, you'll get a pop-up window that lets you add a publisher. After you
287 successfully create the publisher in the pop-up, the "Add book" form will be
288 updated with the newly created publisher. Slick.
289
290 How the Admin Site Works
291 ========================
292
293 Behind the scenes, how does the admin site work? It's pretty straightforward.
294
295 When Django loads your URLconf from ``urls.py`` at server startup, it executes
296 the ``admin.autodiscover()`` statement that we added as part of activating the
297 admin. This function iterates over your ``INSTALLED_APPS`` setting and looks
298 for a file called ``admin.py`` in each installed app. If an ``admin.py``
299 exists in a given app, it executes the code in that file.
300
301 In the ``admin.py`` in our ``books`` app, each call to
302 ``admin.site.register()`` simply registers the given model with the admin. The
303 admin site will only display an edit/change interface for models that have been
304 explicitly registered.
305
306 The app ``django.contrib.auth`` includes its own ``admin.py``, which is why
307 Users and Groups showed up automatically in the admin. Other ``django.contrib``
308 apps, such as ``django.contrib.redirects``, also add themselves to the admin,
309 as do many third-party Django applications you might download from the Web.
310
311 Beyond that, the Django admin site is just a Django application, with its own
312 models, templates, views and URLpatterns. You add it to your application by
313 hooking it into your URLconf, just as you hook in your own views. You can
314 inspect its templates, views and URLpatterns by poking around in
315 ``django/contrib/admin`` in your copy of the Django codebase -- but don't be
316 tempted to change anything directly in there, as there are plenty of hooks for
317 you to customize the way the admin site works. (If you do decide to poke around
318 the Django admin application, keep in mind it does some rather complicated
319 things in reading metadata about models, so it would probably take a good
320 amount of time to read and understand the code.)
321
322 Making Fields Optional
323 ======================
324
325 After you play around with the admin site for a while, you'll probably notice a
326 limitation -- the edit forms require every field to be filled out, whereas in
327 many cases you'd want certain fields to be optional. Let's say, for example,
328 that we want our ``Author`` model's ``email`` field to be optional -- that is,
329 a blank string should be allowed. In the real world, you might not have an
330 e-mail address on file for every author.
331
fa81ebb @Meliowant Update chapter06.rst
Meliowant authored
332 To specify that the ``email`` field is optional, edit the ``Author`` model
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
333 (which, as you'll recall from Chapter 5, lives in ``mysite/books/models.py``).
334 Simply add ``blank=True`` to the ``email`` field, like so:
335
336 .. parsed-literal::
337
338 class Author(models.Model):
339 first_name = models.CharField(max_length=30)
340 last_name = models.CharField(max_length=40)
341 email = models.EmailField(**blank=True**)
342
343 .. SL Tested ok
344
345 This tells Django that a blank value is indeed allowed for authors' e-mail
346 addresses. By default, all fields have ``blank=False``, which means blank
347 values are not allowed.
348
349 There's something interesting happening here. Until now, with the exception of
350 the ``__unicode__()`` method, our models have served as definitions of our
351 database tables -- Pythonic expressions of SQL ``CREATE TABLE`` statements,
352 essentially. In adding ``blank=True``, we have begun expanding our model beyond
353 a simple definition of what the database table looks like. Now, our model class
354 is starting to become a richer collection of knowledge about what ``Author``
355 objects are and what they can do. Not only is the ``email`` field represented
356 by a ``VARCHAR`` column in the database; it's also an optional field in
357 contexts such as the Django admin site.
358
359 Once you've added that ``blank=True``, reload the "Add author" edit form
360 (``http://127.0.0.1:8000/admin/books/author/add/``), and you'll notice the
361 field's label -- "Email" -- is no longer bolded. This signifies it's not a
362 required field. You can now add authors without needing to provide
363 e-mail addresses; you won't get the loud red "This field is required" message
364 anymore, if the field is submitted empty.
365
366 Making Date and Numeric Fields Optional
367 ---------------------------------------
368
369 A common gotcha related to ``blank=True`` has to do with date and numeric
370 fields, but it requires a fair amount of background explanation.
371
372 SQL has its own way of specifying blank values -- a special value called
373 ``NULL``. ``NULL`` could mean "unknown," or "invalid," or some other
374 application-specific meaning.
375
376 In SQL, a value of ``NULL`` is different than an empty string, just as the
377 special Python object ``None`` is different than an empty Python string
378 (``""``). This means it's possible for a particular character field (e.g., a
379 ``VARCHAR`` column) to contain both ``NULL`` values and empty string values.
380
381 This can cause unwanted ambiguity and confusion: "Why does this record have a
382 ``NULL`` but this other one has an empty string? Is there a difference, or was
383 the data just entered inconsistently?" And: "How do I get all the records that
384 have a blank value -- should I look for both ``NULL`` records and empty
385 strings, or do I only select the ones with empty strings?"
386
387 To help avoid such ambiguity, Django's automatically generated ``CREATE TABLE``
388 statements (which were covered in Chapter 5) add an explicit ``NOT NULL`` to
389 each column definition. For example, here's the generated statement for our
390 ``Author`` model, from Chapter 5::
391
392 CREATE TABLE "books_author" (
393 "id" serial NOT NULL PRIMARY KEY,
394 "first_name" varchar(30) NOT NULL,
395 "last_name" varchar(40) NOT NULL,
396 "email" varchar(75) NOT NULL
397 )
398 ;
399
400 In most cases, this default behavior is optimal for your application and will
401 save you from data-inconsistency headaches. And it works nicely with the rest
402 of Django, such as the Django admin site, which inserts an empty string (*not*
403 a ``NULL`` value) when you leave a character field blank.
404
405 But there's an exception with database column types that do not accept empty
406 strings as valid values -- such as dates, times and numbers. If you try to
407 insert an empty string into a date or integer column, you'll likely get a
408 database error, depending on which database you're using. (PostgreSQL, which is
409 strict, will raise an exception here; MySQL might accept it or might not,
410 depending on the version you're using, the time of day and the phase of the
411 moon.) In this case, ``NULL`` is the only way to specify an empty
412 value. In Django models, you can specify that ``NULL`` is allowed by adding
413 ``null=True`` to a field.
414
415 So that's a long way of saying this: if you want to allow blank values in a
416 date field (e.g., ``DateField``, ``TimeField``, ``DateTimeField``) or numeric
417 field (e.g., ``IntegerField``, ``DecimalField``, ``FloatField``), you'll need
418 to use both ``null=True`` *and* ``blank=True``.
419
420 For sake of example, let's change our ``Book`` model to allow a blank
421 ``publication_date``. Here's the revised code:
422
423 .. parsed-literal::
424
425 class Book(models.Model):
426 title = models.CharField(max_length=100)
427 authors = models.ManyToManyField(Author)
428 publisher = models.ForeignKey(Publisher)
429 publication_date = models.DateField(**blank=True, null=True**)
430
431 .. SL Tested ok
432
433 Adding ``null=True`` is more complicated than adding ``blank=True``, because
434 ``null=True`` changes the semantics of the database -- that is, it changes the
435 ``CREATE TABLE`` statement to remove the ``NOT NULL`` from the
436 ``publication_date`` field. To complete this change, we'll need to update the
437 database.
438
439 For a number of reasons, Django does not attempt to automate changes to
440 database schemas, so it's your own responsibility to execute the appropriate
441 ``ALTER TABLE`` statement whenever you make such a change to a model. Recall
442 that you can use ``manage.py dbshell`` to enter your database server's shell.
443 Here's how to remove the ``NOT NULL`` in this particular case::
444
445 ALTER TABLE books_book ALTER COLUMN publication_date DROP NOT NULL;
446
447 (Note that this SQL syntax is specific to PostgreSQL.)
448
449 We'll cover schema changes in more depth in Chapter 10.
450
451 Bringing this back to the admin site, now the "Add book" edit form should allow
452 for empty publication date values.
453
454 Customizing Field Labels
455 ========================
456
457 On the admin site's edit forms, each field's label is generated from its model
458 field name. The algorithm is simple: Django just replaces underscores with
459 spaces and capitalizes the first character, so, for example, the ``Book``
460 model's ``publication_date`` field has the label "Publication date."
461
462 However, field names don't always lend themselves to nice admin field labels,
463 so in some cases you might want to customize a label. You can do this by
464 specifying ``verbose_name`` in the appropriate model field.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
465
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
466 For example, here's how we can change the label of the ``Author.email`` field
467 to "e-mail," with a hyphen:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
468
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
469 .. parsed-literal::
470
471 class Author(models.Model):
472 first_name = models.CharField(max_length=30)
473 last_name = models.CharField(max_length=40)
474 email = models.EmailField(blank=True, **verbose_name='e-mail'**)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
475
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
476 Make that change and reload the server, and you should see the field's new
477 label on the author edit form.
478
479 Note that you shouldn't capitalize the first letter of a ``verbose_name``
480 unless it should *always* be capitalized (e.g., ``"USA state"``). Django will
481 automatically capitalize it when it needs to, and it will use the exact
482 ``verbose_name`` value in other places that don't require capitalization.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
483
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
484 Finally, note that you can pass the ``verbose_name`` as a positional argument,
485 for a slightly more compact syntax. This example is equivalent to the previous
486 one:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
487
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
488 .. parsed-literal::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
489
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
490 class Author(models.Model):
491 first_name = models.CharField(max_length=30)
492 last_name = models.CharField(max_length=40)
493 email = models.EmailField(**'e-mail',** blank=True)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
494
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
495 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
496
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
497 This won't work with ``ManyToManyField`` or ``ForeignKey`` fields, though,
498 because they require the first argument to be a model class. In those cases,
499 specifying ``verbose_name`` explicitly is the way to go.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
500
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
501 Custom ModelAdmin classes
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
502 =========================
503
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
504 The changes we've made so far -- ``blank=True``, ``null=True`` and
505 ``verbose_name`` -- are really model-level changes, not admin-level changes.
506 That is, these changes are fundamentally a part of the model and just so happen
507 to be used by the admin site; there's nothing admin-specific about them.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
508
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
509 Beyond these, the Django admin site offers a wealth of options that let you
510 customize how the admin site works for a particular model. Such options live in
511 *ModelAdmin classes*, which are classes that contain configuration for a
512 specific model in a specific admin site instance.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
513
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
514 Customizing change lists
515 ------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
516
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
517 Let's dive into admin customization by specifying the fields that are
518 displayed on the change list for our ``Author`` model. By default, the change
519 list displays the result of ``__unicode__()`` for each object. In Chapter 5, we
520 defined the ``__unicode__()`` method for ``Author`` objects to display the
521 first name and last name together:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
522
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
523 .. parsed-literal::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
524
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
525 class Author(models.Model):
526 first_name = models.CharField(max_length=30)
527 last_name = models.CharField(max_length=40)
528 email = models.EmailField(blank=True, verbose_name='e-mail')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
529
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
530 **def __unicode__(self):**
531 **return u'%s %s' % (self.first_name, self.last_name)**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
532
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
533 As a result, the change list for ``Author`` objects displays each other's
534 first name and last name together, as you can see in Figure 6-7.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
535
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
536 .. DWP The image is of the change list for a book, not an author.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
537
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
538 .. figure:: graphics/chapter06/author_changelist1.png
539 :alt: Screenshot of the author change list page.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
540
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
541 Figure 6-7. The author change list page
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
542
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
543 We can improve on this default behavior by adding a few other fields to the
544 change list display. It'd be handy, for example, to see each author's e-mail
545 address in this list, and it'd be nice to be able to sort by first and last
546 name.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
547
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
548 To make this happen, we'll define a ``ModelAdmin`` class for the ``Author``
549 model. This class is the key to customizing the admin, and one of the most
550 basic things it lets you do is specify the list of fields to display on change
551 list pages. Edit ``admin.py`` to make these changes:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
552
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
553 .. parsed-literal::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
554
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
555 from django.contrib import admin
556 from mysite.books.models import Publisher, Author, Book
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
557
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
558 **class AuthorAdmin(admin.ModelAdmin):**
559 **list_display = ('first_name', 'last_name', 'email')**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
560
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
561 admin.site.register(Publisher)
562 **admin.site.register(Author, AuthorAdmin)**
563 admin.site.register(Book)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
564
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
565 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
566
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
567 Here's what we've done:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
568
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
569 * We created the class ``AuthorAdmin``. This class, which subclasses
570 ``django.contrib.admin.ModelAdmin``, holds custom configuration
571 for a specific admin model. We've only specified one customization --
572 ``list_display``, which is set to a tuple of field names to display on
573 the change list page. These field names must exist in the model, of
574 course.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
575
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
576 * We altered the ``admin.site.register()`` call to add ``AuthorAdmin`` after
577 ``Author``. You can read this as: "Register the ``Author`` model with the
578 ``AuthorAdmin`` options."
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
579
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
580 The ``admin.site.register()`` function takes a ``ModelAdmin`` subclass as
581 an optional second argument. If you don't specify a second argument (as
582 is the case for ``Publisher`` and ``Book``), Django will use the default
583 admin options for that model.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
584
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
585 With that tweak made, reload the author change list page, and you'll see it's
586 now displaying three columns -- the first name, last name and e-mail address.
587 In addition, each of those columns is sortable by clicking on the column
588 header. (See Figure 6-8.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
589
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
590 .. figure:: graphics/chapter06/author_changelist2.png
591 :alt: Screenshot of the author change list page after list_display.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
592
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
593 Figure 6-8. The author change list page after list_display
594
595 .. DWP This figure has the same filename as the last one.
596
597 Next, let's add a simple search bar. Add ``search_fields`` to the
598 ``AuthorAdmin``, like so:
599
600 .. parsed-literal::
601
602 class AuthorAdmin(admin.ModelAdmin):
603 list_display = ('first_name', 'last_name', 'email')
604 **search_fields = ('first_name', 'last_name')**
605
606 .. SL Tested ok
607
608 Reload the page in your browser, and you should see a search bar at the top.
609 (See Figure 6-9.) We've just told the admin change list page to include a
610 search bar that searches against the ``first_name`` and ``last_name`` fields.
611 As a user might expect, this is case-insensitive and searches both fields, so
612 searching for the string ``"bar"`` would find both an author with the first
613 name Barney and an author with the last name Hobarson.
614
615 .. DWP Again, same screenshot.
616
617 .. figure:: graphics/chapter06/author_changelist3.png
618 :alt: Screenshot of the author change list page after search_fields.
619
620 Figure 6-9. The author change list page after search_fields
621
622 Next, let's add some date filters to our ``Book`` model's change list page:
623
624 .. parsed-literal::
625
626 from django.contrib import admin
627 from mysite.books.models import Publisher, Author, Book
628
629 class AuthorAdmin(admin.ModelAdmin):
630 list_display = ('first_name', 'last_name', 'email')
631 search_fields = ('first_name', 'last_name')
632
633 **class BookAdmin(admin.ModelAdmin):**
634 **list_display = ('title', 'publisher', 'publication_date')**
635 **list_filter = ('publication_date',)**
636
637 admin.site.register(Publisher)
638 admin.site.register(Author, AuthorAdmin)
639 **admin.site.register(Book, BookAdmin)**
640
641 .. SL Tested ok
642
643 Here, because we're dealing with a different set of options, we created a
644 separate ``ModelAdmin`` class -- ``BookAdmin``. First, we defined a
645 ``list_display`` just to make the change list look a bit nicer. Then, we
646 used ``list_filter``, which is set to a tuple of fields to use to create
647 filters along the right side of the change list page. For date fields, Django
648 provides shortcuts to filter the list to "Today," "Past 7 days," "This month"
649 and "This year" -- shortcuts that Django's developers have found hit the
650 common cases for filtering by date. Figure 6-10 shows what that looks like.
651
652 .. DWP Screenshot needs changing.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
653
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
654 .. figure:: graphics/chapter06/book_changelist1.png
655 :alt: Screenshot of the book change list page after list_filter.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
656
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
657 Figure 6-10. The book change list page after list_filter
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
658
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
659 ``list_filter`` also works on fields of other types, not just ``DateField``.
660 (Try it with ``BooleanField`` and ``ForeignKey`` fields, for example.) The
661 filters show up as long as there are at least 2 values to choose from.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
662
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
663 Another way to offer date filters is to use the ``date_hierarchy`` admin
664 option, like this:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
665
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
666 .. parsed-literal::
667
668 class BookAdmin(admin.ModelAdmin):
669 list_display = ('title', 'publisher', 'publication_date')
670 list_filter = ('publication_date',)
671 **date_hierarchy = 'publication_date'**
672
673 .. SL Tested ok
674
675 With this in place, the change list page gets a date drill-down navigation bar
676 at the top of the list, as shown in Figure 6-11. It starts with a list of
677 available years, then drills down into months and individual days.
678
679 .. DWP Screenshot again.
680
681 .. figure:: graphics/chapter06/book_changelist2.png
682 :alt: Screenshot of the book change list page after date_hierarchy.
683
684 Figure 6-11. The book change list page after date_hierarchy
685
686 Note that ``date_hierarchy`` takes a *string*, not a tuple, because only one
687 date field can be used to make the hierarchy.
688
689 Finally, let's change the default ordering so that books on the change list
690 page are always ordered descending by their publication date. By default,
691 the change list orders objects according to their model's ``ordering`` within
692 ``class Meta`` (which we covered in Chapter 5) -- but you haven't specified
693 this ``ordering`` value, then the ordering is undefined.
694
695 .. parsed-literal::
696
697 class BookAdmin(admin.ModelAdmin):
698 list_display = ('title', 'publisher', 'publication_date')
699 list_filter = ('publication_date',)
700 date_hierarchy = 'publication_date'
701 **ordering = ('-publication_date',)**
702
703 .. SL Tested ok
704
705 This admin ``ordering`` option works exactly as the ``ordering`` in models'
706 ``class Meta``, except that it only uses the first field name in the list. Just
707 pass a list or tuple of field names, and add a minus sign to a field to use
708 descending sort order.
709
710 Reload the book change list to see this in action. Note that the
711 "Publication date" header now includes a small arrow that indicates which way
712 the records are sorted. (See Figure 6-12.)
713
714 .. DWP Different screenshot needed.
715
716 .. figure:: graphics/chapter06/book_changelist3.png
717 :alt: Screenshot of the book change list page after ordering.
718
719 Figure 6-12. The book change list page after ordering
720
721 We've covered the main change list options here. Using these options, you can
722 make a very powerful, production-ready data-editing interface with only a few
723 lines of code.
724
725 Customizing edit forms
726 ----------------------
727
728 Just as the change list can be customized, edit forms can be customized in many
729 ways.
730
731 First, let's customize the way fields are ordered. By default, the order of
732 fields in an edit form corresponds to the order they're defined in the model.
733 We can change that using the ``fields`` option in our ``ModelAdmin`` subclass:
734
735 .. parsed-literal::
736
737 class BookAdmin(admin.ModelAdmin):
738 list_display = ('title', 'publisher', 'publication_date')
739 list_filter = ('publication_date',)
740 date_hierarchy = 'publication_date'
741 ordering = ('-publication_date',)
742 **fields = ('title', 'authors', 'publisher', 'publication_date')**
743
744 .. SL Tested ok
745
746 After this change, the edit form for books will use the given ordering for
747 fields. It's slightly more natural to have the authors after the book title.
748 Of course, the field order should depend on your data-entry workflow. Every
749 form is different.
750
751 Another useful thing the ``fields`` option lets you do is to *exclude* certain
752 fields from being edited entirely. Just leave out the field(s) you want to
753 exclude. You might use this if your admin users are only trusted to edit a
754 certain segment of your data, or if part of your fields are changed by some
755 outside, automated process. For example, in our book database, we could
756 hide the ``publication_date`` field from being editable:
757
758 .. parsed-literal::
759
760 class BookAdmin(admin.ModelAdmin):
761 list_display = ('title', 'publisher', 'publication_date')
762 list_filter = ('publication_date',)
763 date_hierarchy = 'publication_date'
764 ordering = ('-publication_date',)
765 **fields = ('title', 'authors', 'publisher')**
766
767 .. SL Tested ok
768
769 As a result, the edit form for books doesn't offer a way to specify the
770 publication date. This could be useful, say, if you're an editor who prefers
771 that his authors not push back publication dates. (This is purely a
772 hypothetical example, of course.)
773
774 When a user uses this incomplete form to add a new book, Django will simply set
775 the ``publication_date`` to ``None`` -- so make sure that field has
776 ``null=True``.
777
778 Another commonly used edit-form customization has to do with many-to-many
779 fields. As we've seen on the edit form for books, the admin site represents each
780 ``ManyToManyField`` as a multiple-select boxes, which is the most logical
781 HTML input widget to use -- but multiple-select boxes can be difficult to use.
782 If you want to select multiple items, you have to hold down the control key,
783 or command on a Mac, to do so. The admin site helpfully inserts a bit of text
784 that explains this, but, still, it gets unwieldy when your field contains
785 hundreds of options.
786
787 The admin site's solution is ``filter_horizontal``. Let's add that to
788 ``BookAdmin`` and see what it does.
789
790 .. parsed-literal::
791
792 class BookAdmin(admin.ModelAdmin):
793 list_display = ('title', 'publisher', 'publication_date')
794 list_filter = ('publication_date',)
795 date_hierarchy = 'publication_date'
796 ordering = ('-publication_date',)
797 **filter_horizontal = ('authors',)**
798
799 .. SL Tested ok
800
801 (If you're following along, note that we've also removed the ``fields`` option
802 to restore all the fields in the edit form.)
803
804 Reload the edit form for books, and you'll see that the "Authors" section now
805 uses a fancy JavaScript filter interface that lets you search through the
806 options dynamically and move specific authors from "Available authors" to
807 the "Chosen authors" box, and vice versa.
808
809 .. DWP screenshot!
810
811 .. figure:: graphics/chapter06/book_editform1.png
812 :alt: Screenshot of the book edit form after adding filter_horizontal.
813
814 Figure 6-13. The book edit form after adding filter_horizontal
815
816 We'd highly recommend using ``filter_horizontal`` for any ``ManyToManyField``
817 that has more than 10 items. It's far easier to use than a simple
818 multiple-select widget. Also, note you can use ``filter_horizontal``
819 for multiple fields -- just specify each name in the tuple.
820
821 ``ModelAdmin`` classes also support a ``filter_vertical`` option. This works
822 exactly as ``filter_horizontal``, but the resulting JavaScript interface stacks
823 the two boxes vertically instead of horizontally. It's a matter of personal
824 taste.
825
826 ``filter_horizontal`` and ``filter_vertical`` only work on ``ManyToManyField``
827 fields, not ``ForeignKey`` fields. By default, the admin site uses simple
828 ``<select>`` boxes for ``ForeignKey`` fields, but, as for ``ManyToManyField``,
829 sometimes you don't want to incur the overhead of having to select all the
830 related objects to display in the drop-down. For example, if our book database
831 grows to include thousands of publishers, the "Add book" form could take a
832 while to load, because it would have to load every publisher for display in the
833 ``<select>`` box.
834
835 The way to fix this is to use an option called ``raw_id_fields``. Set this to
836 a tuple of ``ForeignKey`` field names, and those fields will be displayed in
837 the admin with a simple text input box (``<input type="text">``) instead of a
838 ``<select>``. See Figure 6-14.
839
840 .. parsed-literal::
841
842 class BookAdmin(admin.ModelAdmin):
843 list_display = ('title', 'publisher', 'publication_date')
844 list_filter = ('publication_date',)
845 date_hierarchy = 'publication_date'
846 ordering = ('-publication_date',)
847 filter_horizontal = ('authors',)
848 **raw_id_fields = ('publisher',)**
849
850 .. SL Tested ok
851
852 .. DWP Screenshot!
853
854 .. figure:: graphics/chapter06/book_editform2.png
855 :alt: Screenshot of edit form after raw_id_fields.
856
857 Figure 6-14. The book edit form after adding raw_id_fields
858
859 What do you enter in this input box? The database ID of the publisher. Given
860 that humans don't normally memorize database IDs, there's also a
861 magnifying-glass icon that you can click to pull up a pop-up window, from which
862 you can select the publisher to add.
863
864 Users, Groups, and Permissions
865 ==============================
866
867 Because you're logged in as a superuser, you have access to create, edit, and
868 delete any object. Naturally, different environments require different
869 permission systems -- not everybody can or should be a superuser. Django's
870 admin site uses a permissions system that you can use to give specific users
871 access only to the portions of the interface that they need.
872
873 These user accounts are meant to be generic enough to be used outside of the
874 admin interface, but we'll just treat them as admin user accounts for now. In
875 Chapter 14, we'll cover how to integrate user accounts with the rest of your
876 site (i.e., not just the admin site).
877
878 You can edit users and permissions through the admin interface just like any
879 other object. We saw this earlier in this chapter, when we played around with
880 the User and Group sections of the admin. User objects have the standard
881 username, password, e-mail and real name fields you might expect, along with a
882 set of fields that define what the user is allowed to do in the admin
883 interface. First, there's a set of three boolean flags:
884
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
885 * The "active" flag controls whether the user is active at all.
886 If this flag is off and the user tries to log in, he won't be allowed in,
887 even with a valid password.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
888
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
889 * The "staff" flag controls whether the user is allowed to log in to the
890 admin interface (i.e., whether that user is considered a "staff member" in
891 your organization). Since this same user system can be used to control
892 access to public (i.e., non-admin) sites (see Chapter 14), this flag
893 differentiates between public users and administrators.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
894
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
895 * The "superuser" flag gives the user full access to add, create and
896 delete any item in the admin interface. If a user has this flag set, then
897 all regular permissions (or lack thereof) are ignored for that user.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
898
899 "Normal" admin users -- that is, active, non-superuser staff members -- are
900 granted admin access through assigned permissions. Each object editable through
901 the admin interface (e.g., books, authors, publishers) has three permissions: a
902 *create* permission, an *edit* permission and a *delete* permission. Assigning
903 permissions to a user grants the user access to do what is described by those
904 permissions.
905
906 When you create a user, that user has no permissions, and it's up to you to
907 give the user specific permissions. For example, you can give a user permission
908 to add and change publishers, but not permission to delete them. Note that
909 these permissions are defined per-model, not per-object -- so they let you say
910 "John can make changes to any book," but they don't let you say "John can make
911 changes to any book published by Apress." The latter functionality, per-object
912 permissions, is a bit more complicated and is outside the scope of this book
913 but is covered in the Django documentation.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
914
915 .. note::
916
917 Access to edit users and permissions is also controlled by this permission
918 system. If you give someone permission to edit users, she will be able to
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
919 edit her own permissions, which might not be what you want! Giving a user
920 permission to edit users is essentially turning a user into a superuser.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
921
922 You can also assign users to groups. A *group* is simply a set of permissions to
923 apply to all members of that group. Groups are useful for granting identical
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
924 permissions to a subset of users.
925
926 When and Why to Use the Admin Interface -- And When Not to
927 ==========================================================
928
929 After having worked through this chapter, you should have a good idea of how to
930 use Django's admin site. But we want to make a point of covering *when* and
931 *why* you might want to use it -- and when *not* to use it.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
932
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
933 Django's admin site especially shines when nontechnical users need to be able
934 to enter data; that's the purpose behind the feature, after all. At the
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
935 newspaper where Django was first developed, development of a typical online
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
936 feature -- say, a special report on water quality in the municipal supply --
937 would go something like this:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
938
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
939 * The reporter responsible for the project meets with one of the developers
940 and describes the available data.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
941
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
942 * The developer designs Django models to fit this data and then opens up
943 the admin site to the reporter.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
944
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
945 * The reporter inspects the admin site to point out any missing or
946 extraneous fields -- better now than later. The developer changes the
947 models iteratively.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
948
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
949 * When the models are agreed upon, the reporter begins entering data using
950 the admin site. At the same time, the programmer can focus on developing
951 the publicly accessible views/templates (the fun part!).
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
952
953 In other words, the raison d'être of Django's admin interface is facilitating
954 the simultaneous work of content producers and programmers.
955
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
956 However, beyond these obvious data entry tasks, the admin site is useful in a
957 few other cases:
958
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
959 * *Inspecting data models*: Once you've defined a few models, it can be
960 quite useful to call them up in the admin interface and enter some dummy
961 data. In some cases, this might reveal data-modeling mistakes or other
962 problems with your models.
963
964 * *Managing acquired data*: For applications that rely on data coming from
965 external sources (e.g., users or Web crawlers), the admin site gives you
966 an easy way to inspect or edit this data. You can think of it as a less
967 powerful, but more convenient, version of your database's command-line
968 utility.
969
970 * *Quick and dirty data-management apps*: You can use the admin site to
971 build yourself a very lightweight data management app -- say, to keep
972 track of expenses. If you're just building something for your own needs,
973 not for public consumption, the admin site can take you a long way. In
974 this sense, you can think of it as a beefed up, relational version of a
975 spreadsheet.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
976
977 One final point we want to make clear is: the admin site is not an
978 end-all-be-all. Over the years, we've seen it hacked and chopped up to serve a
979 variety of functions it wasn't intended to serve. It's not intended to be a
980 *public* interface to data, nor is it intended to allow for sophisticated
981 sorting and searching of your data. As we said early in this chapter, it's for
982 trusted site administrators. Keeping this sweet spot in mind is the key to
983 effective admin-site usage.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
984
985 What's Next?
986 ============
987
988 So far we've created a few models and configured a top-notch interface for
9c98f71 @jay754 fixing mistakes on links
jay754 authored
989 editing data. In the next chapter `Chapter 7`_, we'll move on to the real "meat and potatoes"
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
990 of Web development: form creation and processing.
ebd3449 @jay754 Broken links fix on all chapters
jay754 authored
991
5d4ad88 @belgianguy Removed trailing slash, rst to html
belgianguy authored
992 .. _Chapter 7: chapter07.html
Something went wrong with that request. Please try again.