Fixed #14835 -- Corrected a lack of indentation in the reST markup for docs/ref/contrib/admin/index.txt and reflowed the text accordingly. Thanks to cogat for the report.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@14830 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Gabriel Hurley 2010-12-05 04:52:31 +00:00
parent 4a1f2129d0
commit 01f2081bb6
1 changed files with 626 additions and 604 deletions

View File

@ -62,8 +62,9 @@ Other topics
.. class:: ModelAdmin .. class:: ModelAdmin
The ``ModelAdmin`` class is the representation of a model in the admin The ``ModelAdmin`` class is the representation of a model in the admin
interface. These are stored in a file named ``admin.py`` in your application. interface. These are stored in a file named ``admin.py`` in your
Let's take a look at a very simple example of the ``ModelAdmin``:: application. Let's take a look at a very simple example of
the ``ModelAdmin``::
from django.contrib import admin from django.contrib import admin
from myproject.myapp.models import Author from myproject.myapp.models import Author
@ -98,8 +99,8 @@ subclass::
.. attribute:: ModelAdmin.date_hierarchy .. attribute:: ModelAdmin.date_hierarchy
Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField``
your model, and the change list page will include a date-based drilldown in your model, and the change list page will include a date-based drilldown
navigation by that field. navigation by that field.
Example:: Example::
@ -108,10 +109,10 @@ Example::
.. attribute:: ModelAdmin.form .. attribute:: ModelAdmin.form
By default a ``ModelForm`` is dynamically created for your model. It is used By default a ``ModelForm`` is dynamically created for your model. It is
to create the form presented on both the add/change pages. You can easily used to create the form presented on both the add/change pages. You can
provide your own ``ModelForm`` to override any default form behavior on the easily provide your own ``ModelForm`` to override any default form behavior
add/change pages. on the add/change pages.
For an example see the section `Adding custom validation to the admin`_. For an example see the section `Adding custom validation to the admin`_.
@ -120,15 +121,16 @@ For an example see the section `Adding custom validation to the admin`_.
Set ``fieldsets`` to control the layout of admin "add" and "change" pages. Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
``fieldsets`` is a list of two-tuples, in which each two-tuple represents a ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a
``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of the ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of
form.) the form.)
The two-tuples are in the format ``(name, field_options)``, where ``name`` is a The two-tuples are in the format ``(name, field_options)``, where ``name``
string representing the title of the fieldset and ``field_options`` is a is a string representing the title of the fieldset and ``field_options`` is
dictionary of information about the fieldset, including a list of fields to be a dictionary of information about the fieldset, including a list of fields
displayed in it. to be displayed in it.
A full example, taken from the ``django.contrib.flatpages.FlatPage`` model:: A full example, taken from the :class:`django.contrib.flatpages.FlatPage`
model::
class FlatPageAdmin(admin.ModelAdmin): class FlatPageAdmin(admin.ModelAdmin):
fieldsets = ( fieldsets = (
@ -146,8 +148,8 @@ This results in an admin page that looks like:
.. image:: _images/flatfiles_admin.png .. image:: _images/flatfiles_admin.png
If ``fieldsets`` isn't given, Django will default to displaying each field If ``fieldsets`` isn't given, Django will default to displaying each field
that isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, that isn't an ``AutoField`` and has ``editable=True``, in a single
in the same order as the fields are defined in the model. fieldset, in the same order as the fields are defined in the model.
The ``field_options`` dictionary can have the following keys: The ``field_options`` dictionary can have the following keys:
@ -162,8 +164,8 @@ The ``field_options`` dictionary can have the following keys:
} }
To display multiple fields on the same line, wrap those fields in To display multiple fields on the same line, wrap those fields in
their own tuple. In this example, the ``first_name`` and ``last_name`` their own tuple. In this example, the ``first_name`` and
fields will display on the same line:: ``last_name`` fields will display on the same line::
{ {
'fields': (('first_name', 'last_name'), 'address', 'city', 'state'), 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
@ -184,8 +186,8 @@ The ``field_options`` dictionary can have the following keys:
} }
Two useful classes defined by the default admin site stylesheet are Two useful classes defined by the default admin site stylesheet are
``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style
be initially collapsed in the admin and replaced with a small will be initially collapsed in the admin and replaced with a small
"click to expand" link. Fieldsets with the ``wide`` style will be "click to expand" link. Fieldsets with the ``wide`` style will be
given extra horizontal space. given extra horizontal space.
@ -225,8 +227,8 @@ to be displayed as read-only.
.. attribute:: ModelAdmin.exclude .. attribute:: ModelAdmin.exclude
This attribute, if given, should be a list of field names to exclude from the This attribute, if given, should be a list of field names to exclude from
form. the form.
For example, let's consider the following model:: For example, let's consider the following model::
@ -236,7 +238,8 @@ For example, let's consider the following model::
birth_date = models.DateField(blank=True, null=True) birth_date = models.DateField(blank=True, null=True)
If you want a form for the ``Author`` model that includes only the ``name`` If you want a form for the ``Author`` model that includes only the ``name``
and ``title`` fields, you would specify ``fields`` or ``exclude`` like this:: and ``title`` fields, you would specify ``fields`` or ``exclude`` like
this::
class AuthorAdmin(admin.ModelAdmin): class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title') fields = ('name', 'title')
@ -245,15 +248,15 @@ and ``title`` fields, you would specify ``fields`` or ``exclude`` like this::
exclude = ('birth_date',) exclude = ('birth_date',)
Since the Author model only has three fields, ``name``, ``title``, and Since the Author model only has three fields, ``name``, ``title``, and
``birth_date``, the forms resulting from the above declarations will contain ``birth_date``, the forms resulting from the above declarations will
exactly the same fields. contain exactly the same fields.
.. attribute:: ModelAdmin.filter_horizontal .. attribute:: ModelAdmin.filter_horizontal
Use a nifty unobtrusive JavaScript "filter" interface instead of the Use a nifty unobtrusive JavaScript "filter" interface instead of the
usability-challenged ``<select multiple>`` in the admin form. The value is a usability-challenged ``<select multiple>`` in the admin form. The value is
list of fields that should be displayed as a horizontal filter interface. See a list of fields that should be displayed as a horizontal filter interface.
``filter_vertical`` to use a vertical interface. See ``filter_vertical`` to use a vertical interface.
.. attribute:: ModelAdmin.filter_vertical .. attribute:: ModelAdmin.filter_vertical
@ -262,15 +265,15 @@ interface.
.. attribute:: ModelAdmin.list_display .. attribute:: ModelAdmin.list_display
Set ``list_display`` to control which fields are displayed on the change list Set ``list_display`` to control which fields are displayed on the change
page of the admin. list page of the admin.
Example:: Example::
list_display = ('first_name', 'last_name') list_display = ('first_name', 'last_name')
If you don't set ``list_display``, the admin site will display a single column If you don't set ``list_display``, the admin site will display a single
that displays the ``__unicode__()`` representation of each object. column that displays the ``__unicode__()`` representation of each object.
You have four possible values that can be used in ``list_display``: You have four possible values that can be used in ``list_display``:
@ -289,8 +292,8 @@ You have four possible values that can be used in ``list_display``:
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = (upper_case_name,) list_display = (upper_case_name,)
* A string representing an attribute on the ``ModelAdmin``. This behaves * A string representing an attribute on the ``ModelAdmin``. This
same as the callable. For example:: behaves same as the callable. For example::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('upper_case_name',) list_display = ('upper_case_name',)
@ -319,19 +322,20 @@ A few special cases to note about ``list_display``:
* If the field is a ``ForeignKey``, Django will display the * If the field is a ``ForeignKey``, Django will display the
``__unicode__()`` of the related object. ``__unicode__()`` of the related object.
* ``ManyToManyField`` fields aren't supported, because that would entail * ``ManyToManyField`` fields aren't supported, because that would
executing a separate SQL statement for each row in the table. If you entail executing a separate SQL statement for each row in the table.
want to do this nonetheless, give your model a custom method, and add If you want to do this nonetheless, give your model a custom method,
that method's name to ``list_display``. (See below for more on custom and add that method's name to ``list_display``. (See below for more
methods in ``list_display``.) on custom methods in ``list_display``.)
* If the field is a ``BooleanField`` or ``NullBooleanField``, Django will * If the field is a ``BooleanField`` or ``NullBooleanField``, Django
display a pretty "on" or "off" icon instead of ``True`` or ``False``. will display a pretty "on" or "off" icon instead of ``True`` or
``False``.
* If the string given is a method of the model, ``ModelAdmin`` or a * If the string given is a method of the model, ``ModelAdmin`` or a
callable, Django will HTML-escape the output by default. If you'd rather callable, Django will HTML-escape the output by default. If you'd
not escape the output of the method, give the method an ``allow_tags`` rather not escape the output of the method, give the method an
attribute whose value is ``True``. ``allow_tags`` attribute whose value is ``True``.
Here's a full example model:: Here's a full example model::
@ -348,9 +352,9 @@ A few special cases to note about ``list_display``:
list_display = ('first_name', 'last_name', 'colored_name') list_display = ('first_name', 'last_name', 'colored_name')
* If the string given is a method of the model, ``ModelAdmin`` or a * If the string given is a method of the model, ``ModelAdmin`` or a
callable that returns True or False Django will display a pretty "on" or callable that returns True or False Django will display a pretty
"off" icon if you give the method a ``boolean`` attribute whose value is "on" or "off" icon if you give the method a ``boolean`` attribute
``True``. whose value is ``True``.
Here's a full example model:: Here's a full example model::
@ -367,18 +371,18 @@ A few special cases to note about ``list_display``:
* The ``__str__()`` and ``__unicode__()`` methods are just as valid in * The ``__str__()`` and ``__unicode__()`` methods are just as valid in
``list_display`` as any other model method, so it's perfectly OK to do ``list_display`` as any other model method, so it's perfectly OK to
this:: do this::
list_display = ('__unicode__', 'some_other_field') list_display = ('__unicode__', 'some_other_field')
* Usually, elements of ``list_display`` that aren't actual database fields * Usually, elements of ``list_display`` that aren't actual database
can't be used in sorting (because Django does all the sorting at the fields can't be used in sorting (because Django does all the sorting
database level). at the database level).
However, if an element of ``list_display`` represents a certain database However, if an element of ``list_display`` represents a certain
field, you can indicate this fact by setting the ``admin_order_field`` database field, you can indicate this fact by setting the
attribute of the item. ``admin_order_field`` attribute of the item.
For example:: For example::
@ -399,22 +403,22 @@ A few special cases to note about ``list_display``:
.. attribute:: ModelAdmin.list_display_links .. attribute:: ModelAdmin.list_display_links
Set ``list_display_links`` to control which fields in ``list_display`` should Set ``list_display_links`` to control which fields in ``list_display``
be linked to the "change" page for an object. should be linked to the "change" page for an object.
By default, the change list page will link the first column -- the first field By default, the change list page will link the first column -- the first
specified in ``list_display`` -- to the change page for each item. But field specified in ``list_display`` -- to the change page for each item.
``list_display_links`` lets you change which columns are linked. Set But ``list_display_links`` lets you change which columns are linked. Set
``list_display_links`` to a list or tuple of field names (in the same format as ``list_display_links`` to a list or tuple of field names (in the same
``list_display``) to link. format as ``list_display``) to link.
``list_display_links`` can specify one or many field names. As long as the ``list_display_links`` can specify one or many field names. As long as the
field names appear in ``list_display``, Django doesn't care how many (or how field names appear in ``list_display``, Django doesn't care how many (or
few) fields are linked. The only requirement is: If you want to use how few) fields are linked. The only requirement is: If you want to use
``list_display_links``, you must define ``list_display``. ``list_display_links``, you must define ``list_display``.
In this example, the ``first_name`` and ``last_name`` fields will be linked on In this example, the ``first_name`` and ``last_name`` fields will be
the change list page:: linked on the change list page::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'birthday') list_display = ('first_name', 'last_name', 'birthday')
@ -426,33 +430,34 @@ the change list page::
.. versionadded:: 1.1 .. versionadded:: 1.1
Set ``list_editable`` to a list of field names on the model which will allow Set ``list_editable`` to a list of field names on the model which will
editing on the change list page. That is, fields listed in ``list_editable`` allow editing on the change list page. That is, fields listed in
will be displayed as form widgets on the change list page, allowing users to ``list_editable`` will be displayed as form widgets on the change list
edit and save multiple rows at once. page, allowing users to edit and save multiple rows at once.
.. note:: .. note::
``list_editable`` interacts with a couple of other options in particular ``list_editable`` interacts with a couple of other options in
ways; you should note the following rules: particular ways; you should note the following rules:
* Any field in ``list_editable`` must also be in ``list_display``. You * Any field in ``list_editable`` must also be in ``list_display``.
can't edit a field that's not displayed! You can't edit a field that's not displayed!
* The same field can't be listed in both ``list_editable`` and * The same field can't be listed in both ``list_editable`` and
``list_display_links`` -- a field can't be both a form and a link. ``list_display_links`` -- a field can't be both a form and
a link.
You'll get a validation error if either of these rules are broken. You'll get a validation error if either of these rules are broken.
.. attribute:: ModelAdmin.list_filter .. attribute:: ModelAdmin.list_filter
Set ``list_filter`` to activate filters in the right sidebar of the change list Set ``list_filter`` to activate filters in the right sidebar of the change
page of the admin. This should be a list of field names, and each specified list page of the admin. This should be a list of field names, and each
field should be either a ``BooleanField``, ``CharField``, ``DateField``, specified field should be either a ``BooleanField``, ``CharField``,
``DateTimeField``, ``IntegerField`` or ``ForeignKey``. ``DateField``, ``DateTimeField``, ``IntegerField`` or ``ForeignKey``.
This example, taken from the ``django.contrib.auth.models.User`` model, shows This example, taken from the ``django.contrib.auth.models.User`` model,
how both ``list_display`` and ``list_filter`` work:: shows how both ``list_display`` and ``list_filter`` work::
class UserAdmin(admin.ModelAdmin): class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
@ -471,33 +476,34 @@ The above code results in an admin change list page that looks like this:
.. attribute:: ModelAdmin.list_per_page .. attribute:: ModelAdmin.list_per_page
Set ``list_per_page`` to control how many items appear on each paginated admin Set ``list_per_page`` to control how many items appear on each paginated
change list page. By default, this is set to ``100``. admin change list page. By default, this is set to ``100``.
.. attribute:: ModelAdmin.list_select_related .. attribute:: ModelAdmin.list_select_related
Set ``list_select_related`` to tell Django to use Set ``list_select_related`` to tell Django to use
:meth:`~django.db.models.QuerySet.select_related` in retrieving the list of :meth:`~django.db.models.QuerySet.select_related` in retrieving the list of
objects on the admin change list page. This can save you a bunch of database objects on the admin change list page. This can save you a bunch of
queries. database queries.
The value should be either ``True`` or ``False``. Default is ``False``. The value should be either ``True`` or ``False``. Default is ``False``.
Note that Django will use :meth:`~django.db.models.QuerySet.select_related`, Note that Django will use :meth:`~django.db.models.QuerySet.select_related`,
regardless of this setting, if one of the ``list_display`` fields is a regardless of this setting if one of the ``list_display`` fields is a
``ForeignKey``. ``ForeignKey``.
.. attribute:: ModelAdmin.inlines .. attribute:: ModelAdmin.inlines
See ``InlineModelAdmin`` objects below. See :class:`InlineModelAdmin` objects below.
.. attribute:: ModelAdmin.ordering .. attribute:: ModelAdmin.ordering
Set ``ordering`` to specify how objects on the admin change list page should be Set ``ordering`` to specify how objects on the admin change list page
ordered. This should be a list or tuple in the same format as a model's should be ordered. This should be a list or tuple in the same format as a
``ordering`` parameter. model's ``ordering`` parameter.
If this isn't provided, the Django admin will use the model's default ordering. If this isn't provided, the Django admin will use the model's default
ordering.
.. admonition:: Note .. admonition:: Note
@ -506,28 +512,28 @@ If this isn't provided, the Django admin will use the model's default ordering.
.. attribute:: ModelAdmin.prepopulated_fields .. attribute:: ModelAdmin.prepopulated_fields
Set ``prepopulated_fields`` to a dictionary mapping field names to the fields Set ``prepopulated_fields`` to a dictionary mapping field names to the
it should prepopulate from:: fields it should prepopulate from::
class ArticleAdmin(admin.ModelAdmin): class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)} prepopulated_fields = {"slug": ("title",)}
When set, the given fields will use a bit of JavaScript to populate from the When set, the given fields will use a bit of JavaScript to populate from
fields assigned. The main use for this functionality is to automatically the fields assigned. The main use for this functionality is to
generate the value for ``SlugField`` fields from one or more other fields. The automatically generate the value for ``SlugField`` fields from one or more
generated value is produced by concatenating the values of the source fields, other fields. The generated value is produced by concatenating the values
and then by transforming that result into a valid slug (e.g. substituting of the source fields, and then by transforming that result into a valid
dashes for spaces). slug (e.g. substituting dashes for spaces).
``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``, nor ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,
``ManyToManyField`` fields. nor ``ManyToManyField`` fields.
.. attribute:: ModelAdmin.radio_fields .. attribute:: ModelAdmin.radio_fields
By default, Django's admin uses a select-box interface (<select>) for By default, Django's admin uses a select-box interface (<select>) for
fields that are ``ForeignKey`` or have ``choices`` set. If a field is present fields that are ``ForeignKey`` or have ``choices`` set. If a field is
in ``radio_fields``, Django will use a radio-button interface instead. present in ``radio_fields``, Django will use a radio-button interface
Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model:: instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
radio_fields = {"group": admin.VERTICAL} radio_fields = {"group": admin.VERTICAL}
@ -546,7 +552,8 @@ overhead of having to select all the related instances to display in the
drop-down. drop-down.
``raw_id_fields`` is a list of fields you would like to change ``raw_id_fields`` is a list of fields you would like to change
into a ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``:: into an ``Input`` widget for either a ``ForeignKey`` or
``ManyToManyField``::
class ArticleAdmin(admin.ModelAdmin): class ArticleAdmin(admin.ModelAdmin):
raw_id_fields = ("newspaper",) raw_id_fields = ("newspaper",)
@ -555,24 +562,24 @@ into a ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
.. versionadded:: 1.2 .. versionadded:: 1.2
By default the admin shows all fields as editable. Any fields in this option By default the admin shows all fields as editable. Any fields in this
(which should be a ``list`` or ``tuple``) will display its data as-is and option (which should be a ``list`` or ``tuple``) will display its data
non-editable. This option behaves nearly identical to :attr:`ModelAdmin.list_display`. as-is and non-editable. This option behaves nearly identical to
Usage is the same, however, when you specify :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.list_display`. Usage is the same, however, when you
:attr:`ModelAdmin.fieldsets` the read-only fields must be present to be shown specify :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` the
(they are ignored otherwise). read-only fields must be present to be shown (they are ignored otherwise).
If ``readonly_fields`` is used without defining explicit ordering through If ``readonly_fields`` is used without defining explicit ordering through
:attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be added :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be
last after all editable fields. added last after all editable fields.
.. attribute:: ModelAdmin.save_as .. attribute:: ModelAdmin.save_as
Set ``save_as`` to enable a "save as" feature on admin change forms. Set ``save_as`` to enable a "save as" feature on admin change forms.
Normally, objects have three save options: "Save", "Save and continue editing" Normally, objects have three save options: "Save", "Save and continue
and "Save and add another". If ``save_as`` is ``True``, "Save and add another" editing" and "Save and add another". If ``save_as`` is ``True``, "Save
will be replaced by a "Save as" button. and add another" will be replaced by a "Save as" button.
"Save as" means the object will be saved as a new object (with a new ID), "Save as" means the object will be saved as a new object (with a new ID),
rather than the old object. rather than the old object.
@ -584,8 +591,9 @@ By default, ``save_as`` is set to ``False``.
Set ``save_on_top`` to add save buttons across the top of your admin change Set ``save_on_top`` to add save buttons across the top of your admin change
forms. forms.
Normally, the save buttons appear only at the bottom of the forms. If you set Normally, the save buttons appear only at the bottom of the forms. If you
``save_on_top``, the buttons will appear both on the top and the bottom. set ``save_on_top``, the buttons will appear both on the top and the
bottom.
By default, ``save_on_top`` is set to ``False``. By default, ``save_on_top`` is set to ``False``.
@ -601,17 +609,18 @@ These fields should be some kind of text field, such as ``CharField`` or
search_fields = ['foreign_key__related_fieldname'] search_fields = ['foreign_key__related_fieldname']
For example, if you have a blog entry with an author, the following definition For example, if you have a blog entry with an author, the following
would enable search blog entries by the email address of the author:: definition would enable search blog entries by the email address of the
author::
search_fields = ['user__email'] search_fields = ['user__email']
When somebody does a search in the admin search box, Django splits the search When somebody does a search in the admin search box, Django splits the
query into words and returns all objects that contain each of the words, case search query into words and returns all objects that contain each of the
insensitive, where each word must be in at least one of ``search_fields``. For words, case insensitive, where each word must be in at least one of
example, if ``search_fields`` is set to ``['first_name', 'last_name']`` and a ``search_fields``. For example, if ``search_fields`` is set to
user searches for ``john lennon``, Django will do the equivalent of this SQL ``['first_name', 'last_name']`` and a user searches for ``john lennon``,
``WHERE`` clause:: Django will do the equivalent of this SQL ``WHERE`` clause::
WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%') WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%') AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
@ -620,19 +629,19 @@ For faster and/or more restrictive searches, prefix the field name
with an operator: with an operator:
``^`` ``^``
Matches the beginning of the field. For example, if ``search_fields`` is Matches the beginning of the field. For example, if ``search_fields``
set to ``['^first_name', '^last_name']`` and a user searches for is set to ``['^first_name', '^last_name']`` and a user searches for
``john lennon``, Django will do the equivalent of this SQL ``WHERE`` ``john lennon``, Django will do the equivalent of this SQL ``WHERE``
clause:: clause::
WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%') WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%') AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
This query is more efficient than the normal ``'%john%'`` query, because This query is more efficient than the normal ``'%john%'`` query,
the database only needs to check the beginning of a column's data, rather because the database only needs to check the beginning of a column's
than seeking through the entire column's data. Plus, if the column has an data, rather than seeking through the entire column's data. Plus, if
index on it, some databases may be able to use the index for this query, the column has an index on it, some databases may be able to use the
even though it's a ``LIKE`` query. index for this query, even though it's a ``LIKE`` query.
``=`` ``=``
Matches exactly, case-insensitive. For example, if Matches exactly, case-insensitive. For example, if
@ -643,13 +652,13 @@ with an operator:
WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john') WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon') AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
Note that the query input is split by spaces, so, following this example, Note that the query input is split by spaces, so, following this
it's currently not possible to search for all records in which example, it's currently not possible to search for all records in which
``first_name`` is exactly ``'john winston'`` (containing a space). ``first_name`` is exactly ``'john winston'`` (containing a space).
``@`` ``@``
Performs a full-text match. This is like the default search method but uses Performs a full-text match. This is like the default search method but
an index. Currently this is only available for MySQL. uses an index. Currently this is only available for MySQL.
.. attribute:: ModelAdmin.formfield_overrides .. attribute:: ModelAdmin.formfield_overrides
@ -660,11 +669,11 @@ This provides a quick-and-dirty way to override some of the
``formfield_overrides`` is a dictionary mapping a field class to a dict of ``formfield_overrides`` is a dictionary mapping a field class to a dict of
arguments to pass to the field at construction time. arguments to pass to the field at construction time.
Since that's a bit abstract, let's look at a concrete example. The most common Since that's a bit abstract, let's look at a concrete example. The most
use of ``formfield_overrides`` is to add a custom widget for a certain type of common use of ``formfield_overrides`` is to add a custom widget for a
field. So, imagine we've written a ``RichTextEditorWidget`` that we'd like to certain type of field. So, imagine we've written a ``RichTextEditorWidget``
use for large text fields instead of the default ``<textarea>``. Here's how we'd that we'd like to use for large text fields instead of the default
do that:: ``<textarea>``. Here's how we'd do that::
from django.db import models from django.db import models
from django.contrib import admin from django.contrib import admin
@ -678,20 +687,22 @@ do that::
models.TextField: {'widget': RichTextEditorWidget}, models.TextField: {'widget': RichTextEditorWidget},
} }
Note that the key in the dictionary is the actual field class, *not* a string. Note that the key in the dictionary is the actual field class, *not* a
The value is another dictionary; these arguments will be passed to string. The value is another dictionary; these arguments will be passed to
:meth:`~django.forms.Field.__init__`. See :doc:`/ref/forms/api` for details. :meth:`~django.forms.Field.__init__`. See :doc:`/ref/forms/api` for
details.
.. warning:: .. warning::
If you want to use a custom widget with a relation field (i.e. If you want to use a custom widget with a relation field (i.e.
:class:`~django.db.models.ForeignKey` or :class:`~django.db.models.ForeignKey` or
:class:`~django.db.models.ManyToManyField`), make sure you haven't included :class:`~django.db.models.ManyToManyField`), make sure you haven't
that field's name in ``raw_id_fields`` or ``radio_fields``. included that field's name in ``raw_id_fields`` or ``radio_fields``.
``formfield_overrides`` won't let you change the widget on relation fields ``formfield_overrides`` won't let you change the widget on relation
that have ``raw_id_fields`` or ``radio_fields`` set. That's because fields that have ``raw_id_fields`` or ``radio_fields`` set. That's
``raw_id_fields`` and ``radio_fields`` imply custom widgets of their own. because ``raw_id_fields`` and ``radio_fields`` imply custom widgets of
their own.
.. attribute:: ModelAdmin.actions .. attribute:: ModelAdmin.actions
@ -771,8 +782,8 @@ templates used by the :class:`ModelAdmin` views:
.. method:: ModelAdmin.save_model(self, request, obj, form, change) .. method:: ModelAdmin.save_model(self, request, obj, form, change)
The ``save_model`` method is given the ``HttpRequest``, a model instance, The ``save_model`` method is given the ``HttpRequest``, a model instance,
a ``ModelForm`` instance and a boolean value based on whether it is adding or a ``ModelForm`` instance and a boolean value based on whether it is adding
changing the object. Here you can do any pre- or post-save operations. or changing the object. Here you can do any pre- or post-save operations.
For example to attach ``request.user`` to the object prior to saving:: For example to attach ``request.user`` to the object prior to saving::
@ -785,8 +796,8 @@ For example to attach ``request.user`` to the object prior to saving::
.. versionadded:: 1.3 .. versionadded:: 1.3
The ``delete_model`` method is given the ``HttpRequest`` and a model instance. The ``delete_model`` method is given the ``HttpRequest`` and a model
Use this method to do pre- or post-delete operations. instance. Use this method to do pre- or post-delete operations.
.. method:: ModelAdmin.save_formset(self, request, form, formset, change) .. method:: ModelAdmin.save_formset(self, request, form, formset, change)
@ -810,17 +821,17 @@ model instance::
.. versionadded:: 1.2 .. versionadded:: 1.2
The ``get_readonly_fields`` method is given the ``HttpRequest`` and the The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
``obj`` being edited (or ``None`` on an add form) and is expected to return a ``obj`` being edited (or ``None`` on an add form) and is expected to return
``list`` or ``tuple`` of field names that will be displayed as read-only, as a ``list`` or ``tuple`` of field names that will be displayed as read-only,
described above in the :attr:`ModelAdmin.readonly_fields` section. as described above in the :attr:`ModelAdmin.readonly_fields` section.
.. method:: ModelAdmin.get_urls(self) .. method:: ModelAdmin.get_urls(self)
.. versionadded:: 1.1 .. versionadded:: 1.1
The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
that ModelAdmin in the same way as a URLconf. Therefore you can extend them as that ModelAdmin in the same way as a URLconf. Therefore you can extend
documented in :doc:`/topics/http/urls`:: them as documented in :doc:`/topics/http/urls`::
class MyModelAdmin(admin.ModelAdmin): class MyModelAdmin(admin.ModelAdmin):
def get_urls(self): def get_urls(self):
@ -834,22 +845,23 @@ documented in :doc:`/topics/http/urls`::
Notice that the custom patterns are included *before* the regular admin Notice that the custom patterns are included *before* the regular admin
URLs: the admin URL patterns are very permissive and will match nearly URLs: the admin URL patterns are very permissive and will match nearly
anything, so you'll usually want to prepend your custom URLs to the built-in anything, so you'll usually want to prepend your custom URLs to the
ones. built-in ones.
However, the ``self.my_view`` function registered above suffers from two However, the ``self.my_view`` function registered above suffers from two
problems: problems:
* It will *not* perform any permission checks, so it will be accessible to * It will *not* perform any permission checks, so it will be accessible
the general public. to the general public.
* It will *not* provide any header details to prevent caching. This means if * It will *not* provide any header details to prevent caching. This means
the page retrieves data from the database, and caching middleware is if the page retrieves data from the database, and caching middleware is
active, the page could show outdated information. active, the page could show outdated information.
Since this is usually not what you want, Django provides a convenience wrapper Since this is usually not what you want, Django provides a convenience
to check permissions and mark the view as non-cacheable. This wrapper is wrapper to check permissions and mark the view as non-cacheable. This
:meth:`AdminSite.admin_view` (i.e. ``self.admin_site.admin_view`` inside a wrapper is :meth:`AdminSite.admin_view` (i.e.
``ModelAdmin`` instance); use it like so:: ``self.admin_site.admin_view`` inside a ``ModelAdmin`` instance); use it
like so::
class MyModelAdmin(admin.ModelAdmin): class MyModelAdmin(admin.ModelAdmin):
def get_urls(self): def get_urls(self):
@ -863,12 +875,13 @@ Notice the wrapped view in the fifth line above::
(r'^my_view/$', self.admin_site.admin_view(self.my_view)) (r'^my_view/$', self.admin_site.admin_view(self.my_view))
This wrapping will protect ``self.my_view`` from unauthorized access and will This wrapping will protect ``self.my_view`` from unauthorized access and
apply the ``django.views.decorators.cache.never_cache`` decorator to make sure will apply the ``django.views.decorators.cache.never_cache`` decorator to
it is not cached if the cache middleware is active. make sure it is not cached if the cache middleware is active.
If the page is cacheable, but you still want the permission check to be performed, If the page is cacheable, but you still want the permission check to be
you can pass a ``cacheable=True`` argument to :meth:`AdminSite.admin_view`:: performed, you can pass a ``cacheable=True`` argument to
:meth:`AdminSite.admin_view`::
(r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True)) (r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))
@ -886,18 +899,19 @@ return a subset of objects for this foreign key field based on the user::
kwargs["queryset"] = Car.objects.filter(owner=request.user) kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key field This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
to only display the cars owned by the ``User`` instance. field to only display the cars owned by the ``User`` instance.
.. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs) .. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs)
.. versionadded:: 1.1 .. versionadded:: 1.1
Like the ``formfield_for_foreignkey`` method, the ``formfield_for_manytomany`` Like the ``formfield_for_foreignkey`` method, the
method can be overridden to change the default formfield for a many to many ``formfield_for_manytomany`` method can be overridden to change the
field. For example, if an owner can own multiple cars and cars can belong default formfield for a many to many field. For example, if an owner can
to multiple owners -- a many to many relationship -- you could filter the own multiple cars and cars can belong to multiple owners -- a many to
``Car`` foreign key field to only display the cars owned by the ``User``:: many relationship -- you could filter the ``Car`` foreign key field to
only display the cars owned by the ``User``::
class MyModelAdmin(admin.ModelAdmin): class MyModelAdmin(admin.ModelAdmin):
def formfield_for_manytomany(self, db_field, request, **kwargs): def formfield_for_manytomany(self, db_field, request, **kwargs):
@ -932,16 +946,18 @@ Django view for the model instance edition page. See note below.
.. method:: ModelAdmin.changelist_view(self, request, extra_context=None) .. method:: ModelAdmin.changelist_view(self, request, extra_context=None)
Django view for the model instances change list/actions page. See note below. Django view for the model instances change list/actions page. See note
below.
.. method:: ModelAdmin.delete_view(self, request, object_id, extra_context=None) .. method:: ModelAdmin.delete_view(self, request, object_id, extra_context=None)
Django view for the model instance(s) deletion confirmation page. See note below. Django view for the model instance(s) deletion confirmation page. See note
below.
.. method:: ModelAdmin.history_view(self, request, object_id, extra_context=None) .. method:: ModelAdmin.history_view(self, request, object_id, extra_context=None)
Django view for the page that shows the modification history for a given model Django view for the page that shows the modification history for a given
instance. model instance.
Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section, Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
these five methods are in reality designed to be invoked as Django views from these five methods are in reality designed to be invoked as Django views from
@ -997,9 +1013,9 @@ JavaScript without including a second copy, you can use the
Adding custom validation to the admin Adding custom validation to the admin
------------------------------------- -------------------------------------
Adding custom validation of data in the admin is quite easy. The automatic admin Adding custom validation of data in the admin is quite easy. The automatic
interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you admin interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives
the ability define your own form:: you the ability define your own form::
class ArticleAdmin(admin.ModelAdmin): class ArticleAdmin(admin.ModelAdmin):
form = MyArticleAdminForm form = MyArticleAdminForm
@ -1016,8 +1032,8 @@ any field::
# do something that validates your data # do something that validates your data
return self.cleaned_data["name"] return self.cleaned_data["name"]
It is important you use a ``ModelForm`` here otherwise things can break. See the It is important you use a ``ModelForm`` here otherwise things can break. See
:doc:`forms </ref/forms/index>` documentation on :doc:`custom validation the :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
</ref/forms/validation>` and, more specifically, the </ref/forms/validation>` and, more specifically, the
:ref:`model form validation notes <overriding-modelform-clean-method>` for more :ref:`model form validation notes <overriding-modelform-clean-method>` for more
information. information.
@ -1055,7 +1071,8 @@ Django provides two subclasses of ``InlineModelAdmin`` and they are:
* ``TabularInline`` * ``TabularInline``
* ``StackedInline`` * ``StackedInline``
The difference between these two is merely the template used to render them. The difference between these two is merely the template used to render
them.
``InlineModelAdmin`` options ``InlineModelAdmin`` options
----------------------------- -----------------------------
@ -1090,9 +1107,10 @@ all the same functionality as well as some of its own:
.. attribute:: InlineModelAdmin.extra .. attribute:: InlineModelAdmin.extra
This controls the number of extra forms the formset will display in addition This controls the number of extra forms the formset will display in
to the initial forms. See the addition to the initial forms. See the
:doc:`formsets documentation </topics/forms/formsets>` for more information. :doc:`formsets documentation </topics/forms/formsets>` for more
information.
.. versionadded:: 1.2 .. versionadded:: 1.2
@ -1322,8 +1340,8 @@ Overriding Admin Templates
========================== ==========================
It is relatively easy to override many of the templates which the admin module It is relatively easy to override many of the templates which the admin module
uses to generate the various pages of an admin site. You can even override a few uses to generate the various pages of an admin site. You can even override a
of these templates for a specific app, or a specific model. few of these templates for a specific app, or a specific model.
Set up your projects admin template directories Set up your projects admin template directories
----------------------------------------------- -----------------------------------------------
@ -1331,15 +1349,15 @@ Set up your projects admin template directories
The admin template files are located in the ``contrib/admin/templates/admin`` The admin template files are located in the ``contrib/admin/templates/admin``
directory. directory.
In order to override one or more of them, first create an ``admin`` directory in In order to override one or more of them, first create an ``admin`` directory
your project's ``templates`` directory. This can be any of the directories you in your project's ``templates`` directory. This can be any of the directories
specified in ``TEMPLATE_DIRS``. you specified in ``TEMPLATE_DIRS``.
Within this ``admin`` directory, create sub-directories named after your app. Within this ``admin`` directory, create sub-directories named after your app.
Within these app subdirectories create sub-directories named after your models. Within these app subdirectories create sub-directories named after your models.
Note, that the admin app will lowercase the model name when looking for the Note, that the admin app will lowercase the model name when looking for the
directory, so make sure you name the directory in all lowercase if you are going directory, so make sure you name the directory in all lowercase if you are
to run your app on a case-sensitive filesystem. going to run your app on a case-sensitive filesystem.
To override an admin template for a specific app, copy and edit the template To override an admin template for a specific app, copy and edit the template
from the ``django/contrib/admin/templates/admin`` directory, and save it to one from the ``django/contrib/admin/templates/admin`` directory, and save it to one
@ -1409,8 +1427,9 @@ and 500 pages.
Some of the admin templates, such as ``change_list_request.html`` are used Some of the admin templates, such as ``change_list_request.html`` are used
to render custom inclusion tags. These may be overridden, but in such cases to render custom inclusion tags. These may be overridden, but in such cases
you are probably better off creating your own version of the tag in question you are probably better off creating your own version of the tag in
and giving it a different name. That way you can use it selectively. question and giving it a different name. That way you can use it
selectively.
Root and login templates Root and login templates
------------------------ ------------------------
@ -1453,7 +1472,8 @@ Templates can override or extend base admin templates as described in
.. attribute:: AdminSite.index_template .. attribute:: AdminSite.index_template
Path to a custom template that will be used by the admin site main index view. Path to a custom template that will be used by the admin site main index
view.
.. attribute:: AdminSite.login_template .. attribute:: AdminSite.login_template
@ -1463,8 +1483,8 @@ Path to a custom template that will be used by the admin site login view.
.. attribute:: AdminSite.login_form .. attribute:: AdminSite.login_form
Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that will Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that
be used by the admin site login view. will be used by the admin site login view.
.. attribute:: AdminSite.logout_template .. attribute:: AdminSite.logout_template
@ -1476,15 +1496,15 @@ Path to a custom template that will be used by the admin site logout view.
.. versionadded:: 1.2 .. versionadded:: 1.2
Path to a custom template that will be used by the admin site password change Path to a custom template that will be used by the admin site password
view. change view.
.. attribute:: AdminSite.password_change_done_template .. attribute:: AdminSite.password_change_done_template
.. versionadded:: 1.2 .. versionadded:: 1.2
Path to a custom template that will be used by the admin site password change Path to a custom template that will be used by the admin site password
done view. change done view.
Hooking ``AdminSite`` instances into your URLconf Hooking ``AdminSite`` instances into your URLconf
------------------------------------------------- -------------------------------------------------
@ -1619,12 +1639,14 @@ call::
>>> c = Choice.objects.get(...) >>> c = Choice.objects.get(...)
>>> change_url = urlresolvers.reverse('admin:polls_choice_change', args=(c.id,)) >>> change_url = urlresolvers.reverse('admin:polls_choice_change', args=(c.id,))
This will find the first registered instance of the admin application (whatever the instance This will find the first registered instance of the admin application
name), and resolve to the view for changing ``poll.Choice`` instances in that instance. (whatever the instance name), and resolve to the view for changing
``poll.Choice`` instances in that instance.
If you want to find a URL in a specific admin instance, provide the name of that instance If you want to find a URL in a specific admin instance, provide the name of
as a ``current_app`` hint to the reverse call. For example, if you specifically wanted that instance as a ``current_app`` hint to the reverse call. For example,
the admin view from the admin instance named ``custom``, you would need to call:: if you specifically wanted the admin view from the admin instance named
``custom``, you would need to call::
>>> change_url = urlresolvers.reverse('custom:polls_choice_change', args=(c.id,)) >>> change_url = urlresolvers.reverse('custom:polls_choice_change', args=(c.id,))