Django

Code

root/django/branches/newforms-admin/docs/admin.txt

Revision 7873, 23.1 kB (checked in by brosner, 2 months ago)

newforms-admin: Added some documentation about media defintions in ModelAdmin? classes. Fixed #7129.

Line 
1 =====================
2 The Django admin site
3 =====================
4
5 One of the most powerful parts of Django is the automatic admin interface. It
6 reads metadata in your model to provide a powerful and production-ready
7 interface that content producers can immediately use to start adding content to
8 the site. In this document, we discuss how to activate, use and customize
9 Django's admin interface.
10
11 .. admonition:: Note
12
13     The admin site has been refactored significantly since Django 0.96. This
14     document describes the newest version of the admin site, which allows for
15     much richer customization. If you follow the development of Django itself,
16     you may have heard this described as "newforms-admin."
17
18 Overview
19 ========
20
21 There are four steps in activating the Django admin site:
22
23     1. Determine which of your application's models should be editable in the
24        admin interface.
25
26     2. For each of those models, optionally create a ``ModelAdmin`` class that
27        encapsulates the customized admin functionality and options for that
28        particular model.
29
30     3. Instantiate an ``AdminSite`` and tell it about each of your models and
31        ``ModelAdmin`` classes.
32
33     4. Hook the ``AdminSite`` instance into your URLconf.
34
35 ``ModelAdmin`` objects
36 ======================
37
38 The ``ModelAdmin`` class is the representation of a model in the admin
39 interface. These are stored in a file named ``admin.py`` in your application.
40 Let's take a look at a very simple example the ``ModelAdmin``::
41
42     from django.contrib import admin
43     from myproject.myapp.models import Author
44    
45     class AuthorAdmin(admin.ModelAdmin):
46         pass
47     admin.site.register(Author, AuthorAdmin)
48
49 ``ModelAdmin`` Options
50 ----------------------
51
52 The ``ModelAdmin`` is very flexible. It has several options for dealing with
53 customizing the interface. All options are defined on the ``ModelAdmin``
54 subclass::
55
56     class AuthorAdmin(admin.ModelAdmin):
57         date_hierarchy = 'pub_date'
58
59 ``date_hierarchy``
60 ~~~~~~~~~~~~~~~~~~
61
62 Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in
63 your model, and the change list page will include a date-based drilldown
64 navigation by that field.
65
66 Example::
67
68     date_hierarchy = 'pub_date'
69
70 ``fieldsets``
71 ~~~~~~~~~~~~~
72
73 Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
74
75 ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a
76 ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of the
77 form.)
78
79 The two-tuples are in the format ``(name, field_options)``, where ``name`` is a
80 string representing the title of the fieldset and ``field_options`` is a
81 dictionary of information about the fieldset, including a list of fields to be
82 displayed in it.
83
84 A full example, taken from the ``django.contrib.flatpages.FlatPage`` model::
85    
86     class FlatPageAdmin(admin.ModelAdmin):
87         fieldsets = (
88             (None, {
89                 'fields': ('url', 'title', 'content', 'sites')
90             }),
91             ('Advanced options', {
92                 'classes': ('collapse',),
93                 'fields': ('enable_comments', 'registration_required', 'template_name')
94             }),
95         )
96
97 This results in an admin page that looks like:
98
99     .. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png
100
101 If ``fieldsets`` isn't given, Django will default to displaying each field
102 that isn't an ``AutoField`` and has ``editable=True``, in a single fieldset,
103 in the same order as the fields are defined in the model.
104
105 The ``field_options`` dictionary can have the following keys:
106
107 ``fields``
108     A tuple of field names to display in this fieldset. This key is required.
109    
110     Example::
111        
112         {
113         'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
114         }
115
116     To display multiple fields on the same line, wrap those fields in their own
117     tuple. In this example, the ``first_name`` and ``last_name`` fields will
118     display on the same line::
119        
120         {
121         'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
122         }
123
124 ``classes``
125     A string containing extra CSS classes to apply to the fieldset.
126    
127     Example::
128        
129         {
130         'classes': 'wide',
131         }
132
133     Apply multiple classes by separating them with spaces. Example::
134        
135         {
136         'classes': 'wide extrapretty',
137         }
138    
139     Two useful classes defined by the default admin-site stylesheet are
140     ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will be
141     initially collapsed in the admin and replaced with a small "click to expand"
142     link. Fieldsets with the ``wide`` style will be given extra horizontal space.
143
144 ``description``
145     A string of optional extra text to be displayed at the top of each fieldset,
146     under the heading of the fieldset. It's used verbatim, so you can use any HTML
147     and you must escape any special HTML characters (such as ampersands) yourself.
148
149 ``filter_horizontal``
150 ~~~~~~~~~~~~~~~~~~~~~
151
152 Use a nifty unobtrusive Javascript "filter" interface instead of the
153 usability-challenged ``<select multiple>`` in the admin form. The value is a
154 list of fields that should be displayed as a horizontal filter interface. See
155 ``filter_vertical`` to use a vertical interface.
156
157 ``filter_vertical``
158 ~~~~~~~~~~~~~~~~~~~
159
160 Same as ``filter_horizontal``, but is a vertical display of the filter
161 interface.
162
163 ``list_display``
164 ~~~~~~~~~~~~~~~~
165
166 Set ``list_display`` to control which fields are displayed on the change list
167 page of the admin.
168
169 Example::
170
171     list_display = ('first_name', 'last_name')
172
173 If you don't set ``list_display``, the admin site will display a single column
174 that displays the ``__unicode__()`` representation of each object.
175
176 A few special cases to note about ``list_display``:
177
178     * If the field is a ``ForeignKey``, Django will display the
179       ``__unicode__()`` of the related object.
180
181     * ``ManyToManyField`` fields aren't supported, because that would entail
182       executing a separate SQL statement for each row in the table. If you
183       want to do this nonetheless, give your model a custom method, and add
184       that method's name to ``list_display``. (See below for more on custom
185       methods in ``list_display``.)
186
187     * If the field is a ``BooleanField`` or ``NullBooleanField``, Django will
188       display a pretty "on" or "off" icon instead of ``True`` or ``False``.
189
190     * If the string given is a method of the model, Django will call it and
191       display the output. This method should have a ``short_description``
192       function attribute, for use as the header for the field.
193
194       Here's a full example model::
195          
196           class Person(models.Model):
197               name = models.CharField(max_length=50)
198               birthday = models.DateField()
199
200               def decade_born_in(self):
201                   return self.birthday.strftime('%Y')[:3] + "0's"
202               decade_born_in.short_description = 'Birth decade'
203          
204           class PersonAdmin(admin.ModelAdmin):
205               list_display = ('name', 'decade_born_in')
206
207     * If the string given is a method of the model, Django will HTML-escape the
208       output by default. If you'd rather not escape the output of the method,
209       give the method an ``allow_tags`` attribute whose value is ``True``.
210
211       Here's a full example model::
212
213           class Person(models.Model):
214               first_name = models.CharField(max_length=50)
215               last_name = models.CharField(max_length=50)
216               color_code = models.CharField(max_length=6)
217
218               def colored_name(self):
219                   return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
220               colored_name.allow_tags = True
221          
222           class PersonAdmin(admin.ModelAdmin):
223               list_display = ('first_name', 'last_name', 'colored_name')
224
225     * If the string given is a method of the model that returns True or False
226       Django will display a pretty "on" or "off" icon if you give the method a
227       ``boolean`` attribute whose value is ``True``.
228
229       Here's a full example model::
230
231           class Person(models.Model):
232               first_name = models.CharField(max_length=50)
233               birthday = models.DateField()
234
235               def born_in_fifties(self):
236                   return self.birthday.strftime('%Y')[:3] == 5
237               born_in_fifties.boolean = True
238          
239           class PersonAdmin(admin.ModelAdmin):
240               list_display = ('name', 'born_in_fifties')
241
242
243     * The ``__str__()`` and ``__unicode__()`` methods are just as valid in
244       ``list_display`` as any other model method, so it's perfectly OK to do
245       this::
246
247           list_display = ('__unicode__', 'some_other_field')
248
249     * Usually, elements of ``list_display`` that aren't actual database fields
250       can't be used in sorting (because Django does all the sorting at the
251       database level).
252
253       However, if an element of ``list_display`` represents a certain database
254       field, you can indicate this fact by setting the ``admin_order_field``
255       attribute of the item.
256
257       For example::
258
259         class Person(models.Model):
260             first_name = models.CharField(max_length=50)
261             color_code = models.CharField(max_length=6)
262
263             def colored_first_name(self):
264                 return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name)
265             colored_first_name.allow_tags = True
266             colored_first_name.admin_order_field = 'first_name'
267        
268         class PersonAdmin(admin.ModelAdmin):
269             list_display = ('first_name', 'colored_first_name')
270
271       The above will tell Django to order by the ``first_name`` field when
272       trying to sort by ``colored_first_name`` in the admin.
273
274 ``list_display_links``
275 ~~~~~~~~~~~~~~~~~~~~~~
276
277 Set ``list_display_links`` to control which fields in ``list_display`` should
278 be linked to the "change" page for an object.
279
280 By default, the change list page will link the first column -- the first field
281 specified in ``list_display`` -- to the change page for each item. But
282 ``list_display_links`` lets you change which columns are linked. Set
283 ``list_display_links`` to a list or tuple of field names (in the same format as
284 ``list_display``) to link.
285
286 ``list_display_links`` can specify one or many field names. As long as the
287 field names appear in ``list_display``, Django doesn't care how many (or how
288 few) fields are linked. The only requirement is: If you want to use
289 ``list_display_links``, you must define ``list_display``.
290
291 In this example, the ``first_name`` and ``last_name`` fields will be linked on
292 the change list page::
293
294     class PersonAdmin(admin.ModelAdmin):
295         list_display = ('first_name', 'last_name', 'birthday')
296         list_display_links = ('first_name', 'last_name')
297
298 Finally, note that in order to use ``list_display_links``, you must define
299 ``list_display``, too.
300
301 ``list_filter``
302 ~~~~~~~~~~~~~~~
303
304 Set ``list_filter`` to activate filters in the right sidebar of the change list
305 page of the admin. This should be a list of field names, and each specified
306 field should be either a ``BooleanField``, ``CharField``, ``DateField``,
307 ``DateTimeField``, ``IntegerField`` or ``ForeignKey``.
308
309 This example, taken from the ``django.contrib.auth.models.User`` model, shows
310 how both ``list_display`` and ``list_filter`` work::
311
312     class UserAdmin(admin.ModelAdmin):
313         list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
314         list_filter = ('is_staff', 'is_superuser')
315
316 The above code results in an admin change list page that looks like this:
317
318     .. image:: http://media.djangoproject.com/img/doc/users_changelist.png
319
320 (This example also has ``search_fields`` defined. See below.)
321
322 ``list_per_page``
323 ~~~~~~~~~~~~~~~~~
324
325 Set ``list_per_page`` to control how many items appear on each paginated admin
326 change list page. By default, this is set to ``100``.
327
328 ``list_select_related``
329 ~~~~~~~~~~~~~~~~~~~~~~~
330
331 Set ``list_select_related`` to tell Django to use ``select_related()`` in
332 retrieving the list of objects on the admin change list page. This can save you
333 a bunch of database queries.
334
335 The value should be either ``True`` or ``False``. Default is ``False``.
336
337 Note that Django will use ``select_related()``, regardless of this setting,
338 if one of the ``list_display`` fields is a ``ForeignKey``.
339
340 For more on ``select_related()``, see `the select_related() docs`_.
341
342 .. _the select_related() docs: ../db-api/#select-related
343
344 ``inlines``
345 ~~~~~~~~~~~
346
347 See ``InlineModelAdmin`` objects below.
348
349 ``ordering``
350 ~~~~~~~~~~~~
351
352 Set ``ordering`` to specify how objects on the admin change list page should be
353 ordered. This should be a list or tuple in the same format as a model's
354 ``ordering`` parameter.
355
356 If this isn't provided, the Django admin will use the model's default ordering.
357
358 ``prepopulated_fields``
359 ~~~~~~~~~~~~~~~~~~~~~~~
360
361 Set ``prepopulated_fields`` to a dictionary mapping field names to the fields
362 it should prepopulate from::
363
364     class ArticleAdmin(admin.ModelAdmin):
365         prepopulated_fields = {"slug": ("title",)}
366
367 When set the given fields will use a bit of Javascript to populate from the
368 fields assigned.
369
370 ``prepopulated_fields`` doesn't accept DateTimeFields, ForeignKeys nor
371 ManyToManyFields.
372
373 ``radio_fields``
374 ~~~~~~~~~~~~~~~~
375
376 By default, Django's admin uses a select-box interface (<select>) for
377 fields that are ``ForeignKey`` or have ``choices`` set. If a field is present
378 in ``radio_fields``, Django will use a radio-button interface instead.
379 Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
380
381     class PersonAdmin(admin.ModelAdmin):
382         radio_fields = {"group": admin.VERTICAL}
383
384 You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
385 ``django.contrib.admin`` module.
386
387 Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
388 ``choices`` set.
389
390 ``raw_id_fields``
391 ~~~~~~~~~~~~~~~~~
392
393 By default, Django's admin uses a select-box interface (<select>) for
394 fields that are ``ForeignKey``. Sometimes you don't want to incur the
395 overhead of having to select all the related instances to display in the
396 drop-down.
397
398 ``raw_id_fields`` is a list of fields you would like to change
399 into a ``Input`` widget for the primary key.
400
401 ``save_as``
402 ~~~~~~~~~~~
403
404 Set ``save_as`` to enable a "save as" feature on admin change forms.
405
406 Normally, objects have three save options: "Save", "Save and continue editing"
407 and "Save and add another". If ``save_as`` is ``True``, "Save and add another"
408 will be replaced by a "Save as" button.
409
410 "Save as" means the object will be saved as a new object (with a new ID),
411 rather than the old object.
412
413 By default, ``save_as`` is set to ``False``.
414
415 ``save_on_top``
416 ~~~~~~~~~~~~~~~
417
418 Set ``save_on_top`` to add save buttons across the top of your admin change
419 forms.
420
421 Normally, the save buttons appear only at the bottom of the forms. If you set
422 ``save_on_top``, the buttons will appear both on the top and the bottom.
423
424 By default, ``save_on_top`` is set to ``False``.
425
426 ``search_fields``
427 ~~~~~~~~~~~~~~~~~
428
429 Set ``search_fields`` to enable a search box on the admin change list page.
430 This should be set to a list of field names that will be searched whenever
431 somebody submits a search query in that text box.
432
433 These fields should be some kind of text field, such as ``CharField`` or
434 ``TextField``. You can also perform a related lookup on a ``ForeignKey`` with
435 the lookup API "follow" notation::
436
437     search_fields = ['foreign_key__related_fieldname']
438
439 When somebody does a search in the admin search box, Django splits the search
440 query into words and returns all objects that contain each of the words, case
441 insensitive, where each word must be in at least one of ``search_fields``. For
442 example, if ``search_fields`` is set to ``['first_name', 'last_name']`` and a
443 user searches for ``john lennon``, Django will do the equivalent of this SQL
444 ``WHERE`` clause::
445
446     WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
447     AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
448
449 For faster and/or more restrictive searches, prefix the field name
450 with an operator:
451
452 ``^``
453     Matches the beginning of the field. For example, if ``search_fields`` is
454     set to ``['^first_name', '^last_name']`` and a user searches for
455     ``john lennon``, Django will do the equivalent of this SQL ``WHERE``
456     clause::
457
458         WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
459         AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
460
461     This query is more efficient than the normal ``'%john%'`` query, because
462     the database only needs to check the beginning of a column's data, rather
463     than seeking through the entire column's data. Plus, if the column has an
464     index on it, some databases may be able to use the index for this query,
465     even though it's a ``LIKE`` query.
466
467 ``=``
468     Matches exactly, case-insensitive. For example, if
469     ``search_fields`` is set to ``['=first_name', '=last_name']`` and
470     a user searches for ``john lennon``, Django will do the equivalent
471     of this SQL ``WHERE`` clause::
472
473         WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
474         AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
475
476     Note that the query input is split by spaces, so, following this example,
477     it's currently not possible to search for all records in which
478     ``first_name`` is exactly ``'john winston'`` (containing a space).
479
480 ``@``
481     Performs a full-text match. This is like the default search method but uses
482     an index. Currently this is only available for MySQL.
483
484 ``ModelAdmin`` media definitions
485 --------------------------------
486
487 There are times where you would like add a bit of CSS and/or Javascript to
488 the add/change views. This can be accomplished by using a Media inner class
489 on your ``ModelAdmin``::
490
491     class ArticleAdmin(admin.ModelAdmin):
492         class Media:
493             css = {
494                 "all": ("my_styles.css",)
495             }
496             js = ("my_code.js",)
497
498 Keep in mind that this will be prepended with ``MEDIA_URL``. The same rules
499 apply as `regular media definitions on forms`_.
500
501 .. _regular media definitions on forms: ../newforms/#media
502
503 ``InlineModelAdmin`` objects
504 ============================
505
506 The admin interface has the ability to edit models on the same page as a
507 parent model. These are called inlines. You can add them a model being
508 specifing them in a ``ModelAdmin.inlines`` attribute::
509
510     class BookInline(admin.TabularInline):
511         model = Book
512    
513     class AuthorAdmin(admin.ModelAdmin):
514         inlines = [
515             BookInline,
516         ]
517
518 Django provides two subclasses of ``InlineModelAdmin`` and they are::
519
520     * ``TabularInline``
521     * ``StackedInline``
522
523 The difference between these two is merely the template used to render them.
524
525 ``InlineModelAdmin`` options
526 -----------------------------
527
528 The ``InlineModelAdmin`` class is a subclass of ``ModelAdmin`` so it inherits
529 all the same functionality as well as some of its own:
530
531 ``model``
532 ~~~~~~~~~
533
534 The model in which the inline is using. This is required.
535
536 ``fk_name``
537 ~~~~~~~~~~~
538
539 The name of the foreign key on the model. In most cases this will be dealt
540 with automatically, but ``fk_name`` must be specified explicitly if there are
541 more than one foreign key to the same parent model.
542
543 ``formset``
544 ~~~~~~~~~~~
545
546 This defaults to ``BaseInlineFormset``. Using your own formset can give you
547 many possibilities of customization. Inlines are built around
548 `model formsets`_.
549
550 .. _model formsets: ../modelforms/#model-formsets
551
552 ``form``
553 ~~~~~~~~
554
555 The value for ``form`` is inherited from ``ModelAdmin``. This is what is
556 passed through to ``formset_factory`` when creating the formset for this
557 inline.
558
559 ``extra``
560 ~~~~~~~~~
561
562 This controls the number of extra forms the formset will display in addition
563 to the initial forms. See the `formsets documentation`_ for more information.
564
565 .. _formsets documentation: ../newforms/#formsets
566
567 ``max_num``
568 ~~~~~~~~~~~
569
570 This controls the maximum number of forms to show in the inline. This doesn't
571 directly corrolate to the number of objects, but can if the value is small
572 enough. See `max_num in formsets`_ for more information.
573
574 .. _max_num in formsets: ../modelforms/#limiting-the-number-of-objects-editable
575
576 ``template``
577 ~~~~~~~~~~~~
578
579 The template used to render the inline on the page.
580
581 ``verbose_name``
582 ~~~~~~~~~~~~~~~~
583
584 An override to the ``verbose_name`` found in the model's inner ``Meta`` class.
585
586 ``verbose_name_plural``
587 ~~~~~~~~~~~~~~~~~~~~~~~
588
589 An override to the ``verbose_name_plural`` found in the model's inner ``Meta``
590 class.
591
592 Working with a model with two or more foreign keys to the same parent model
593 ---------------------------------------------------------------------------
594
595 It is sometimes possible to have more than one foreign key to the same model.
596 Take this model for instance::
597
598     class Friendship(models.Model):
599         to_person = models.ForeignKey(Person, related_name="friends")
600         from_person = models.ForeignKey(Person, related_name="from_friends")
601    
602 If you wanted to display an inline on the ``Person`` admin add/change pages
603 you need to explicitly define the foreign key since it is unable to do so
604 automatically::
605
606     class FriendshipInline(admin.TabularInline):
607         model = Friendship
608         fk_name = "to_person"
609    
610     class PersonAdmin(admin.ModelAdmin):
611         inlines = [
612             FriendshipInline,
613         ]
614
615 ``AdminSite`` objects
616 =====================
617
618 Hooking ``AdminSite`` instances into your URLconf
619 -------------------------------------------------
620
621 The last step in setting up the Django admin is to hook your ``AdminSite``
622 instance into your URLconf. Do this by pointing a given URL at the
623 ``AdminSite.root`` method.
624
625 In this example, we register the default ``AdminSite`` instance
626 ``django.contrib.admin.site`` at the URL ``/admin/`` ::
627
628     # urls.py
629     from django.conf.urls.defaults import *
630     from django.contrib import admin
631    
632     admin.autodiscover()
633
634     urlpatterns = patterns('',
635         ('^admin/(.*)', admin.site.root),
636     )
637
638 Above we used ``admin.autodiscover()`` to automatically load the
639 ``INSTALLED_APPS`` admin.py modules.
640
641 In this example, we register the ``AdminSite`` instance
642 ``myproject.admin.admin_site`` at the URL ``/myadmin/`` ::
643
644     # urls.py
645     from django.conf.urls.defaults import *
646     from myproject.admin import admin_site
647
648     urlpatterns = patterns('',
649         ('^myadmin/(.*)', admin_site.root),
650     )
651
652 There is really no need to use autodiscover when using your own ``AdminSite``
653 instance since you will likely be importing all the per-app admin.py modules
654 in your ``myproject.admin`` module.
655
656 Note that the regular expression in the URLpattern *must* group everything in
657 the URL that comes after the URL root -- hence the ``(.*)`` in these examples.
658
659 Multiple admin sites in the same URLconf
660 ----------------------------------------
661
662 It's easy to create multiple instances of the admin site on the same
663 Django-powered Web site. Just create multiple instances of ``AdminSite`` and
664 root each one at a different URL.
665
666 In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
667 separate versions of the admin site -- using the ``AdminSite`` instances
668 ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
669 respectively::
670
671     # urls.py
672     from django.conf.urls.defaults import *
673     from myproject.admin import basic_site, advanced_site
674
675     urlpatterns = patterns('',
676         ('^basic-admin/(.*)', basic_site.root),
677         ('^advanced-admin/(.*)', advanced_site.root),
678     )
Note: See TracBrowser for help on using the browser.