Debian Codegraph @

docs/ref/contrib/admin/index.txt

raw
1 =====================
2 The Django admin site
3 =====================
4
5 .. module:: django.contrib.admin
6 :synopsis: Django's admin site.
7
8 One of the most powerful parts of Django is the automatic admin interface. It
9 reads metadata from your models to provide a quick, model-centric interface
10 where trusted users can manage content on your site. The admin's recommended
11 use is limited to an organization's internal management tool. It's not intended
12 for building your entire front end around.
13
14 The admin has many hooks for customization, but beware of trying to use those
15 hooks exclusively. If you need to provide a more process-centric interface
16 that abstracts away the implementation details of database tables and fields,
17 then it's probably time to write your own views.
18
19 In this document we discuss how to activate, use, and customize Django's admin
20 interface.
21
22 Overview
23 ========
24
25 The admin is enabled in the default project template used by
26 :djadmin:`startproject`.
27
28 If you're not using the default project template, here are the requirements:
29
30 #. Add ``'django.contrib.admin'`` and its dependencies -
31 :mod:`django.contrib.auth`, :mod:`django.contrib.contenttypes`,
32 :mod:`django.contrib.messages`, and :mod:`django.contrib.sessions` - to your
33 :setting:`INSTALLED_APPS` setting.
34
35 #. Configure a :class:`~django.template.backends.django.DjangoTemplates`
36 backend in your :setting:`TEMPLATES` setting with
37 ``django.template.context_processors.request``,
38 ``django.contrib.auth.context_processors.auth``, and
39 ``django.contrib.messages.context_processors.messages`` in
40 the ``'context_processors'`` option of :setting:`OPTIONS
41 <TEMPLATES-OPTIONS>`.
42
43 #. If you've customized the :setting:`MIDDLEWARE` setting,
44 :class:`django.contrib.sessions.middleware.SessionMiddleware`,
45 :class:`django.contrib.auth.middleware.AuthenticationMiddleware`, and
46 :class:`django.contrib.messages.middleware.MessageMiddleware` must be
47 included.
48
49 #. :ref:`Hook the admin's URLs into your URLconf
50 <hooking-adminsite-to-urlconf>`.
51
52 After you've taken these steps, you'll be able to use the admin site by
53 visiting the URL you hooked it into (``/admin/``, by default).
54
55 If you need to create a user to login with, use the :djadmin:`createsuperuser`
56 command. By default, logging in to the admin requires that the user has the
57 :attr:`~.User.is_staff` attribute set to ``True``.
58
59 Finally, determine which of your application's models should be editable in the
60 admin interface. For each of those models, register them with the admin as
61 described in :class:`ModelAdmin`.
62
63 Other topics
64 ------------
65
66 .. toctree::
67 :maxdepth: 1
68
69 actions
70 filters
71 admindocs
72 javascript
73
74 .. seealso::
75
76 For information about serving the static files (images, JavaScript, and
77 CSS) associated with the admin in production, see :ref:`serving-files`.
78
79 Having problems? Try :doc:`/faq/admin`.
80
81 ``ModelAdmin`` objects
82 ======================
83
84 .. class:: ModelAdmin
85
86 The ``ModelAdmin`` class is the representation of a model in the admin
87 interface. Usually, these are stored in a file named ``admin.py`` in your
88 application. Let's take a look at an example of the ``ModelAdmin``::
89
90 from django.contrib import admin
91 from myapp.models import Author
92
93
94 class AuthorAdmin(admin.ModelAdmin):
95 pass
96
97
98 admin.site.register(Author, AuthorAdmin)
99
100 .. admonition:: Do you need a ``ModelAdmin`` object at all?
101
102 In the preceding example, the ``ModelAdmin`` class doesn't define any
103 custom values (yet). As a result, the default admin interface will be
104 provided. If you are happy with the default admin interface, you don't
105 need to define a ``ModelAdmin`` object at all -- you can register the
106 model class without providing a ``ModelAdmin`` description. The
107 preceding example could be simplified to::
108
109 from django.contrib import admin
110 from myapp.models import Author
111
112 admin.site.register(Author)
113
114 The ``register`` decorator
115 --------------------------
116
117 .. function:: register(*models, site=django.contrib.admin.sites.site)
118
119 There is also a decorator for registering your ``ModelAdmin`` classes::
120
121 from django.contrib import admin
122 from .models import Author
123
124
125 @admin.register(Author)
126 class AuthorAdmin(admin.ModelAdmin):
127 pass
128
129 It's given one or more model classes to register with the ``ModelAdmin``.
130 If you're using a custom :class:`AdminSite`, pass it using the ``site`` keyword
131 argument::
132
133 from django.contrib import admin
134 from .models import Author, Editor, Reader
135 from myproject.admin_site import custom_admin_site
136
137
138 @admin.register(Author, Reader, Editor, site=custom_admin_site)
139 class PersonAdmin(admin.ModelAdmin):
140 pass
141
142 You can't use this decorator if you have to reference your model admin
143 class in its ``__init__()`` method, e.g.
144 ``super(PersonAdmin, self).__init__(*args, **kwargs)``. You can use
145 ``super().__init__(*args, **kwargs)``.
146
147 Discovery of admin files
148 ------------------------
149
150 When you put ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS`
151 setting, Django automatically looks for an ``admin`` module in each
152 application and imports it.
153
154 .. class:: apps.AdminConfig
155
156 This is the default :class:`~django.apps.AppConfig` class for the admin.
157 It calls :func:`~django.contrib.admin.autodiscover()` when Django starts.
158
159 .. class:: apps.SimpleAdminConfig
160
161 This class works like :class:`~django.contrib.admin.apps.AdminConfig`,
162 except it doesn't call :func:`~django.contrib.admin.autodiscover()`.
163
164 .. attribute:: default_site
165
166 A dotted import path to the default admin site's class or to a callable
167 that returns a site instance. Defaults to
168 ``'django.contrib.admin.sites.AdminSite'``. See
169 :ref:`overriding-default-admin-site` for usage.
170
171 .. function:: autodiscover
172
173 This function attempts to import an ``admin`` module in each installed
174 application. Such modules are expected to register models with the admin.
175
176 Typically you won't need to call this function directly as
177 :class:`~django.contrib.admin.apps.AdminConfig` calls it when Django starts.
178
179 If you are using a custom ``AdminSite``, it is common to import all of the
180 ``ModelAdmin`` subclasses into your code and register them to the custom
181 ``AdminSite``. In that case, in order to disable auto-discovery, you should
182 put ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of
183 ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting.
184
185 ``ModelAdmin`` options
186 ----------------------
187
188 The ``ModelAdmin`` is very flexible. It has several options for dealing with
189 customizing the interface. All options are defined on the ``ModelAdmin``
190 subclass::
191
192 from django.contrib import admin
193
194
195 class AuthorAdmin(admin.ModelAdmin):
196 date_hierarchy = "pub_date"
197
198 .. attribute:: ModelAdmin.actions
199
200 A list of actions to make available on the change list page. See
201 :doc:`/ref/contrib/admin/actions` for details.
202
203 .. attribute:: ModelAdmin.actions_on_top
204 .. attribute:: ModelAdmin.actions_on_bottom
205
206 Controls where on the page the actions bar appears. By default, the admin
207 changelist displays actions at the top of the page (``actions_on_top = True;
208 actions_on_bottom = False``).
209
210 .. attribute:: ModelAdmin.actions_selection_counter
211
212 Controls whether a selection counter is displayed next to the action dropdown.
213 By default, the admin changelist will display it
214 (``actions_selection_counter = True``).
215
216 .. attribute:: ModelAdmin.date_hierarchy
217
218 Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField``
219 in your model, and the change list page will include a date-based drilldown
220 navigation by that field.
221
222 Example::
223
224 date_hierarchy = "pub_date"
225
226 You can also specify a field on a related model using the ``__`` lookup,
227 for example::
228
229 date_hierarchy = "author__pub_date"
230
231 This will intelligently populate itself based on available data,
232 e.g. if all the dates are in one month, it'll show the day-level
233 drill-down only.
234
235 .. note::
236
237 ``date_hierarchy`` uses :meth:`QuerySet.datetimes()
238 <django.db.models.query.QuerySet.datetimes>` internally. Please refer
239 to its documentation for some caveats when time zone support is
240 enabled (:setting:`USE_TZ = True <USE_TZ>`).
241
242 .. attribute:: ModelAdmin.empty_value_display
243
244 This attribute overrides the default display value for record's fields that
245 are empty (``None``, empty string, etc.). The default value is ``-`` (a
246 dash). For example::
247
248 from django.contrib import admin
249
250
251 class AuthorAdmin(admin.ModelAdmin):
252 empty_value_display = "-empty-"
253
254 You can also override ``empty_value_display`` for all admin pages with
255 :attr:`AdminSite.empty_value_display`, or for specific fields like this::
256
257 from django.contrib import admin
258
259
260 class AuthorAdmin(admin.ModelAdmin):
261 list_display = ["name", "title", "view_birth_date"]
262
263 @admin.display(empty_value="???")
264 def view_birth_date(self, obj):
265 return obj.birth_date
266
267 .. attribute:: ModelAdmin.exclude
268
269 This attribute, if given, should be a list of field names to exclude from
270 the form.
271
272 For example, let's consider the following model::
273
274 from django.db import models
275
276
277 class Author(models.Model):
278 name = models.CharField(max_length=100)
279 title = models.CharField(max_length=3)
280 birth_date = models.DateField(blank=True, null=True)
281
282 If you want a form for the ``Author`` model that includes only the ``name``
283 and ``title`` fields, you would specify ``fields`` or ``exclude`` like
284 this::
285
286 from django.contrib import admin
287
288
289 class AuthorAdmin(admin.ModelAdmin):
290 fields = ["name", "title"]
291
292
293 class AuthorAdmin(admin.ModelAdmin):
294 exclude = ["birth_date"]
295
296 Since the Author model only has three fields, ``name``, ``title``, and
297 ``birth_date``, the forms resulting from the above declarations will
298 contain exactly the same fields.
299
300 .. attribute:: ModelAdmin.fields
301
302 Use the ``fields`` option to make simple layout changes in the forms on
303 the "add" and "change" pages such as showing only a subset of available
304 fields, modifying their order, or grouping them into rows. For example, you
305 could define a simpler version of the admin form for the
306 :class:`django.contrib.flatpages.models.FlatPage` model as follows::
307
308 class FlatPageAdmin(admin.ModelAdmin):
309 fields = ["url", "title", "content"]
310
311 In the above example, only the fields ``url``, ``title`` and ``content``
312 will be displayed, sequentially, in the form. ``fields`` can contain
313 values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as
314 read-only.
315
316 For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets` option.
317
318 The ``fields`` option accepts the same types of values as
319 :attr:`~ModelAdmin.list_display`, except that callables and ``__`` lookups
320 for related fields aren't accepted. Names of model and model admin methods
321 will only be used if they're listed in :attr:`~ModelAdmin.readonly_fields`.
322
323 To display multiple fields on the same line, wrap those fields in their own
324 tuple. In this example, the ``url`` and ``title`` fields will display on the
325 same line and the ``content`` field will be displayed below them on its
326 own line::
327
328 class FlatPageAdmin(admin.ModelAdmin):
329 fields = [("url", "title"), "content"]
330
331 .. admonition:: Possible confusion with the ``ModelAdmin.fieldsets`` option
332
333 This ``fields`` option should not be confused with the ``fields``
334 dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
335 as described in the next section.
336
337 If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,
338 Django will default to displaying each field that isn't an ``AutoField`` and
339 has ``editable=True``, in a single fieldset, in the same order as the fields
340 are defined in the model, followed by any fields defined in
341 :attr:`~ModelAdmin.readonly_fields`.
342
343 .. attribute:: ModelAdmin.fieldsets
344
345 Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
346
347 ``fieldsets`` is a list of 2-tuples, in which each 2-tuple represents a
348 ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of
349 the form.)
350
351 The 2-tuples are in the format ``(name, field_options)``, where ``name``
352 is a string representing the title of the fieldset and ``field_options`` is
353 a dictionary of information about the fieldset, including a list of fields
354 to be displayed in it.
355
356 A full example, taken from the
357 :class:`django.contrib.flatpages.models.FlatPage` model::
358
359 from django.contrib import admin
360
361
362 class FlatPageAdmin(admin.ModelAdmin):
363 fieldsets = [
364 (
365 None,
366 {
367 "fields": ["url", "title", "content", "sites"],
368 },
369 ),
370 (
371 "Advanced options",
372 {
373 "classes": ["collapse"],
374 "fields": ["registration_required", "template_name"],
375 },
376 ),
377 ]
378
379 This results in an admin page that looks like:
380
381 .. image:: _images/fieldsets.png
382
383 If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,
384 Django will default to displaying each field that isn't an ``AutoField`` and
385 has ``editable=True``, in a single fieldset, in the same order as the fields
386 are defined in the model.
387
388 The ``field_options`` dictionary can have the following keys:
389
390 * ``fields``
391 A list or tuple of field names to display in this fieldset. This key is
392 required.
393
394 Example::
395
396 {
397 "fields": ["first_name", "last_name", "address", "city", "state"],
398 }
399
400 As with the :attr:`~ModelAdmin.fields` option, to display multiple
401 fields on the same line, wrap those fields in their own tuple. In this
402 example, the ``first_name`` and ``last_name`` fields will display on
403 the same line::
404
405 {
406 "fields": [("first_name", "last_name"), "address", "city", "state"],
407 }
408
409 ``fields`` can contain values defined in
410 :attr:`~ModelAdmin.readonly_fields` to be displayed as read-only.
411
412 If you add the name of a callable to ``fields``, the same rule applies
413 as with the :attr:`~ModelAdmin.fields` option: the callable must be
414 listed in :attr:`~ModelAdmin.readonly_fields`.
415
416 * ``classes``
417 A list or tuple containing extra CSS classes to apply to the fieldset.
418 This can include any custom CSS class defined in the project, as well
419 as any of the CSS classes provided by Django. Within the default admin
420 site CSS stylesheet, two particularly useful classes are defined:
421 ``collapse`` and ``wide``.
422
423 Example::
424
425 {
426 "classes": ["wide", "collapse"],
427 }
428
429 Fieldsets with the ``wide`` style will be given extra horizontal
430 space in the admin interface.
431 Fieldsets with a name and the ``collapse`` style will be initially
432 collapsed, using an expandable widget with a toggle for switching
433 their visibility.
434
435 .. versionchanged:: 5.1
436
437 ``fieldsets`` using the ``collapse`` class now use ``<details>``
438 and ``<summary>`` elements, provided they define a ``name``.
439
440 * ``description``
441 A string of optional extra text to be displayed at the top of each
442 fieldset, under the heading of the fieldset.
443
444 Note that this value is *not* HTML-escaped when it's displayed in
445 the admin interface. This lets you include HTML if you so desire.
446 Alternatively you can use plain text and
447 :func:`django.utils.html.escape` to escape any HTML special
448 characters.
449
450 .. admonition:: :class:`~django.contrib.admin.TabularInline` has limited
451 support for ``fieldsets``
452
453 Using ``fieldsets`` with :class:`~django.contrib.admin.TabularInline`
454 has limited functionality. You can specify which fields will be
455 displayed and their order within the ``TabularInline`` layout by
456 defining ``fields`` in the ``field_options`` dictionary.
457
458 All other features are not supported. This includes the use of ``name``
459 to define a title for a group of fields.
460
461 .. attribute:: ModelAdmin.filter_horizontal
462
463 By default, a :class:`~django.db.models.ManyToManyField` is displayed in
464 the admin site with a ``<select multiple>``. However, multiple-select boxes
465 can be difficult to use when selecting many items. Adding a
466 :class:`~django.db.models.ManyToManyField` to this list will instead use
467 a nifty unobtrusive JavaScript "filter" interface that allows searching
468 within the options. The unselected and selected options appear in two boxes
469 side by side. See :attr:`~ModelAdmin.filter_vertical` to use a vertical
470 interface.
471
472 .. attribute:: ModelAdmin.filter_vertical
473
474 Same as :attr:`~ModelAdmin.filter_horizontal`, but uses a vertical display
475 of the filter interface with the box of unselected options appearing above
476 the box of selected options.
477
478 .. attribute:: ModelAdmin.form
479
480 By default a ``ModelForm`` is dynamically created for your model. It is
481 used to create the form presented on both the add/change pages. You can
482 easily provide your own ``ModelForm`` to override any default form behavior
483 on the add/change pages. Alternatively, you can customize the default
484 form rather than specifying an entirely new one by using the
485 :meth:`ModelAdmin.get_form` method.
486
487 For an example see the section :ref:`admin-custom-validation`.
488
489 .. admonition:: Omit the ``Meta.model`` attribute
490
491 If you define the ``Meta.model`` attribute on a
492 :class:`~django.forms.ModelForm`, you must also define the
493 ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
494 since the admin has its own way of defining fields, the ``Meta.fields``
495 attribute will be ignored.
496
497 If the ``ModelForm`` is only going to be used for the admin, the easiest
498 solution is to omit the ``Meta.model`` attribute, since ``ModelAdmin``
499 will provide the correct model to use. Alternatively, you can set
500 ``fields = []`` in the ``Meta`` class to satisfy the validation on the
501 ``ModelForm``.
502
503 .. admonition:: ``ModelAdmin.exclude`` takes precedence
504
505 If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``
506 option then ``ModelAdmin`` takes precedence::
507
508 from django import forms
509 from django.contrib import admin
510 from myapp.models import Person
511
512
513 class PersonForm(forms.ModelForm):
514 class Meta:
515 model = Person
516 exclude = ["name"]
517
518
519 class PersonAdmin(admin.ModelAdmin):
520 exclude = ["age"]
521 form = PersonForm
522
523 In the above example, the "age" field will be excluded but the "name"
524 field will be included in the generated form.
525
526 .. attribute:: ModelAdmin.formfield_overrides
527
528 This provides a quick-and-dirty way to override some of the
529 :class:`~django.forms.Field` options for use in the admin.
530 ``formfield_overrides`` is a dictionary mapping a field class to a dict of
531 arguments to pass to the field at construction time.
532
533 Since that's a bit abstract, let's look at a concrete example. The most
534 common use of ``formfield_overrides`` is to add a custom widget for a
535 certain type of field. So, imagine we've written a ``RichTextEditorWidget``
536 that we'd like to use for large text fields instead of the default
537 ``<textarea>``. Here's how we'd do that::
538
539 from django.contrib import admin
540 from django.db import models
541
542 # Import our custom widget and our model from where they're defined
543 from myapp.models import MyModel
544 from myapp.widgets import RichTextEditorWidget
545
546
547 class MyModelAdmin(admin.ModelAdmin):
548 formfield_overrides = {
549 models.TextField: {"widget": RichTextEditorWidget},
550 }
551
552 Note that the key in the dictionary is the actual field class, *not* a
553 string. The value is another dictionary; these arguments will be passed to
554 the form field's ``__init__()`` method. See :doc:`/ref/forms/api` for
555 details.
556
557 .. warning::
558
559 If you want to use a custom widget with a relation field (i.e.
560 :class:`~django.db.models.ForeignKey` or
561 :class:`~django.db.models.ManyToManyField`), make sure you haven't
562 included that field's name in ``raw_id_fields``, ``radio_fields``, or
563 ``autocomplete_fields``.
564
565 ``formfield_overrides`` won't let you change the widget on relation
566 fields that have ``raw_id_fields``, ``radio_fields``, or
567 ``autocomplete_fields`` set. That's because ``raw_id_fields``,
568 ``radio_fields``, and ``autocomplete_fields`` imply custom widgets of
569 their own.
570
571 .. attribute:: ModelAdmin.inlines
572
573 See :class:`InlineModelAdmin` objects below as well as
574 :meth:`ModelAdmin.get_formsets_with_inlines`.
575
576 .. attribute:: ModelAdmin.list_display
577
578 Set ``list_display`` to control which fields are displayed on the change
579 list page of the admin.
580
581 Example::
582
583 list_display = ["first_name", "last_name"]
584
585 If you don't set ``list_display``, the admin site will display a single
586 column that displays the ``__str__()`` representation of each object.
587
588 There are five types of values that can be used in ``list_display``. All
589 but the simplest may use the :func:`~django.contrib.admin.display`
590 decorator, which is used to customize how the field is presented:
591
592 * The name of a model field. For example::
593
594 class PersonAdmin(admin.ModelAdmin):
595 list_display = ["first_name", "last_name"]
596
597 * The name of a related field, using the ``__`` notation. For example::
598
599 class PersonAdmin(admin.ModelAdmin):
600 list_display = ["city__name"]
601
602 * A callable that accepts one argument, the model instance. For example::
603
604 @admin.display(description="Name")
605 def upper_case_name(obj):
606 return f"{obj.first_name} {obj.last_name}".upper()
607
608
609 class PersonAdmin(admin.ModelAdmin):
610 list_display = [upper_case_name]
611
612 * A string representing a ``ModelAdmin`` method that accepts one argument,
613 the model instance. For example::
614
615 class PersonAdmin(admin.ModelAdmin):
616 list_display = ["upper_case_name"]
617
618 @admin.display(description="Name")
619 def upper_case_name(self, obj):
620 return f"{obj.first_name} {obj.last_name}".upper()
621
622 * A string representing a model attribute or method (without any required
623 arguments). For example::
624
625 from django.contrib import admin
626 from django.db import models
627
628
629 class Person(models.Model):
630 name = models.CharField(max_length=50)
631 birthday = models.DateField()
632
633 @admin.display(description="Birth decade")
634 def decade_born_in(self):
635 decade = self.birthday.year // 10 * 10
636 return f"{decade}’s"
637
638
639 class PersonAdmin(admin.ModelAdmin):
640 list_display = ["name", "decade_born_in"]
641
642 .. versionchanged:: 5.1
643
644 Support for using ``__`` lookups was added, when targeting related
645 fields.
646
647 A few special cases to note about ``list_display``:
648
649 * If the field is a ``ForeignKey``, Django will display the
650 ``__str__()`` of the related object.
651
652 * ``ManyToManyField`` fields aren't supported, because that would
653 entail executing a separate SQL statement for each row in the table.
654 If you want to do this nonetheless, give your model a custom method,
655 and add that method's name to ``list_display``. (See below for more
656 on custom methods in ``list_display``.)
657
658 * If the field is a ``BooleanField``, Django will display a pretty "yes",
659 "no", or "unknown" icon instead of ``True``, ``False``, or ``None``.
660
661 * If the string given is a method of the model, ``ModelAdmin`` or a
662 callable, Django will HTML-escape the output by default. To escape
663 user input and allow your own unescaped tags, use
664 :func:`~django.utils.html.format_html`.
665
666 Here's a full example model::
667
668 from django.contrib import admin
669 from django.db import models
670 from django.utils.html import format_html
671
672
673 class Person(models.Model):
674 first_name = models.CharField(max_length=50)
675 last_name = models.CharField(max_length=50)
676 color_code = models.CharField(max_length=6)
677
678 @admin.display
679 def colored_name(self):
680 return format_html(
681 '<span style="color: #{};">{} {}</span>',
682 self.color_code,
683 self.first_name,
684 self.last_name,
685 )
686
687
688 class PersonAdmin(admin.ModelAdmin):
689 list_display = ["first_name", "last_name", "colored_name"]
690
691 * As some examples have already demonstrated, when using a callable, a
692 model method, or a ``ModelAdmin`` method, you can customize the column's
693 title by wrapping the callable with the
694 :func:`~django.contrib.admin.display` decorator and passing the
695 ``description`` argument.
696
697 * If the value of a field is ``None``, an empty string, or an iterable
698 without elements, Django will display ``-`` (a dash). You can override
699 this with :attr:`AdminSite.empty_value_display`::
700
701 from django.contrib import admin
702
703 admin.site.empty_value_display = "(None)"
704
705 You can also use :attr:`ModelAdmin.empty_value_display`::
706
707 class PersonAdmin(admin.ModelAdmin):
708 empty_value_display = "unknown"
709
710 Or on a field level::
711
712 class PersonAdmin(admin.ModelAdmin):
713 list_display = ["name", "birth_date_view"]
714
715 @admin.display(empty_value="unknown")
716 def birth_date_view(self, obj):
717 return obj.birth_date
718
719 * If the string given is a method of the model, ``ModelAdmin`` or a
720 callable that returns ``True``, ``False``, or ``None``, Django will
721 display a pretty "yes", "no", or "unknown" icon if you wrap the method
722 with the :func:`~django.contrib.admin.display` decorator passing the
723 ``boolean`` argument with the value set to ``True``::
724
725 from django.contrib import admin
726 from django.db import models
727
728
729 class Person(models.Model):
730 first_name = models.CharField(max_length=50)
731 birthday = models.DateField()
732
733 @admin.display(boolean=True)
734 def born_in_fifties(self):
735 return 1950 <= self.birthday.year < 1960
736
737
738 class PersonAdmin(admin.ModelAdmin):
739 list_display = ["name", "born_in_fifties"]
740
741 * The ``__str__()`` method is just as valid in ``list_display`` as any
742 other model method, so it's perfectly OK to do this::
743
744 list_display = ["__str__", "some_other_field"]
745
746 * Usually, elements of ``list_display`` that aren't actual database
747 fields can't be used in sorting (because Django does all the sorting
748 at the database level).
749
750 However, if an element of ``list_display`` represents a certain database
751 field, you can indicate this fact by using the
752 :func:`~django.contrib.admin.display` decorator on the method, passing
753 the ``ordering`` argument::
754
755 from django.contrib import admin
756 from django.db import models
757 from django.utils.html import format_html
758
759
760 class Person(models.Model):
761 first_name = models.CharField(max_length=50)
762 color_code = models.CharField(max_length=6)
763
764 @admin.display(ordering="first_name")
765 def colored_first_name(self):
766 return format_html(
767 '<span style="color: #{};">{}</span>',
768 self.color_code,
769 self.first_name,
770 )
771
772
773 class PersonAdmin(admin.ModelAdmin):
774 list_display = ["first_name", "colored_first_name"]
775
776 The above will tell Django to order by the ``first_name`` field when
777 trying to sort by ``colored_first_name`` in the admin.
778
779 To indicate descending order with the ``ordering`` argument you can use a
780 hyphen prefix on the field name. Using the above example, this would look
781 like::
782
783 @admin.display(ordering="-first_name")
784 def colored_first_name(self): ...
785
786 The ``ordering`` argument supports query lookups to sort by values on
787 related models. This example includes an "author first name" column in
788 the list display and allows sorting it by first name::
789
790 class Blog(models.Model):
791 title = models.CharField(max_length=255)
792 author = models.ForeignKey(Person, on_delete=models.CASCADE)
793
794
795 class BlogAdmin(admin.ModelAdmin):
796 list_display = ["title", "author", "author_first_name"]
797
798 @admin.display(ordering="author__first_name")
799 def author_first_name(self, obj):
800 return obj.author.first_name
801
802 :doc:`Query expressions </ref/models/expressions>` may be used with the
803 ``ordering`` argument::
804
805 from django.db.models import Value
806 from django.db.models.functions import Concat
807
808
809 class Person(models.Model):
810 first_name = models.CharField(max_length=50)
811 last_name = models.CharField(max_length=50)
812
813 @admin.display(ordering=Concat("first_name", Value(" "), "last_name"))
814 def full_name(self):
815 return self.first_name + " " + self.last_name
816
817 * Elements of ``list_display`` can also be properties
818 ::
819
820 class Person(models.Model):
821 first_name = models.CharField(max_length=50)
822 last_name = models.CharField(max_length=50)
823
824 @property
825 @admin.display(
826 ordering="last_name",
827 description="Full name of the person",
828 boolean=False,
829 )
830 def full_name(self):
831 return self.first_name + " " + self.last_name
832
833
834 class PersonAdmin(admin.ModelAdmin):
835 list_display = ["full_name"]
836
837 Note that ``@property`` must be above ``@display``. If you're using the
838 old way -- setting the display-related attributes directly rather than
839 using the :func:`~django.contrib.admin.display` decorator -- be aware
840 that the ``property()`` function and **not** the ``@property`` decorator
841 must be used::
842
843 def my_property(self):
844 return self.first_name + " " + self.last_name
845
846
847 my_property.short_description = "Full name of the person"
848 my_property.admin_order_field = "last_name"
849 my_property.boolean = False
850
851 full_name = property(my_property)
852
853 * The field names in ``list_display`` will also appear as CSS classes in
854 the HTML output, in the form of ``column-<field_name>`` on each ``<th>``
855 element. This can be used to set column widths in a CSS file for example.
856
857 * Django will try to interpret every element of ``list_display`` in this
858 order:
859
860 * A field of the model or from a related field.
861 * A callable.
862 * A string representing a ``ModelAdmin`` attribute.
863 * A string representing a model attribute.
864
865 For example if you have ``first_name`` as a model field and
866 as a ``ModelAdmin`` attribute, the model field will be used.
867
868
869 .. attribute:: ModelAdmin.list_display_links
870
871 Use ``list_display_links`` to control if and which fields in
872 :attr:`list_display` should be linked to the "change" page for an object.
873
874 By default, the change list page will link the first column -- the first
875 field specified in ``list_display`` -- to the change page for each item.
876 But ``list_display_links`` lets you change this:
877
878 * Set it to ``None`` to get no links at all.
879 * Set it to a list or tuple of fields (in the same format as
880 ``list_display``) whose columns you want converted to links.
881
882 You can specify one or many fields. As long as the fields appear in
883 ``list_display``, Django doesn't care how many (or how few) fields are
884 linked. The only requirement is that if you want to use
885 ``list_display_links`` in this fashion, you must define ``list_display``.
886
887 In this example, the ``first_name`` and ``last_name`` fields will be
888 linked on the change list page::
889
890 class PersonAdmin(admin.ModelAdmin):
891 list_display = ["first_name", "last_name", "birthday"]
892 list_display_links = ["first_name", "last_name"]
893
894 In this example, the change list page grid will have no links::
895
896 class AuditEntryAdmin(admin.ModelAdmin):
897 list_display = ["timestamp", "message"]
898 list_display_links = None
899
900 .. _admin-list-editable:
901
902 .. attribute:: ModelAdmin.list_editable
903
904 Set ``list_editable`` to a list of field names on the model which will
905 allow editing on the change list page. That is, fields listed in
906 ``list_editable`` will be displayed as form widgets on the change list
907 page, allowing users to edit and save multiple rows at once.
908
909 .. note::
910
911 ``list_editable`` interacts with a couple of other options in
912 particular ways; you should note the following rules:
913
914 * Any field in ``list_editable`` must also be in ``list_display``.
915 You can't edit a field that's not displayed!
916
917 * The same field can't be listed in both ``list_editable`` and
918 ``list_display_links`` -- a field can't be both a form and
919 a link.
920
921 You'll get a validation error if either of these rules are broken.
922
923 .. attribute:: ModelAdmin.list_filter
924
925 Set ``list_filter`` to activate filters in the right sidebar of the change
926 list page of the admin.
927
928 At it's simplest ``list_filter`` takes a list or tuple of field names to
929 activate filtering upon, but several more advanced options as available.
930 See :ref:`modeladmin-list-filters` for the details.
931
932 .. attribute:: ModelAdmin.list_max_show_all
933
934 Set ``list_max_show_all`` to control how many items can appear on a "Show
935 all" admin change list page. The admin will display a "Show all" link on the
936 change list only if the total result count is less than or equal to this
937 setting. By default, this is set to ``200``.
938
939 .. attribute:: ModelAdmin.list_per_page
940
941 Set ``list_per_page`` to control how many items appear on each paginated
942 admin change list page. By default, this is set to ``100``.
943
944 .. attribute:: ModelAdmin.list_select_related
945
946 Set ``list_select_related`` to tell Django to use
947 :meth:`~django.db.models.query.QuerySet.select_related` in retrieving
948 the list of objects on the admin change list page. This can save you a
949 bunch of database queries.
950
951 The value should be either a boolean, a list or a tuple. Default is
952 ``False``.
953
954 When value is ``True``, ``select_related()`` will always be called. When
955 value is set to ``False``, Django will look at ``list_display`` and call
956 ``select_related()`` if any ``ForeignKey`` is present.
957
958 If you need more fine-grained control, use a tuple (or list) as value for
959 ``list_select_related``. Empty tuple will prevent Django from calling
960 ``select_related`` at all. Any other tuple will be passed directly to
961 ``select_related`` as parameters. For example::
962
963 class ArticleAdmin(admin.ModelAdmin):
964 list_select_related = ["author", "category"]
965
966 will call ``select_related('author', 'category')``.
967
968 If you need to specify a dynamic value based on the request, you can
969 implement a :meth:`~ModelAdmin.get_list_select_related` method.
970
971 .. note::
972
973 ``ModelAdmin`` ignores this attribute when
974 :meth:`~django.db.models.query.QuerySet.select_related` was already
975 called on the changelist's ``QuerySet``.
976
977 .. attribute:: ModelAdmin.ordering
978
979 Set ``ordering`` to specify how lists of objects should be ordered in the
980 Django admin views. This should be a list or tuple in the same format as a
981 model's :attr:`~django.db.models.Options.ordering` parameter.
982
983 If this isn't provided, the Django admin will use the model's default
984 ordering.
985
986 If you need to specify a dynamic order (for example depending on user or
987 language) you can implement a :meth:`~ModelAdmin.get_ordering` method.
988
989 .. admonition:: Performance considerations with ordering and sorting
990
991 To ensure a deterministic ordering of results, the changelist adds
992 ``pk`` to the ordering if it can't find a single or unique together set
993 of fields that provide total ordering.
994
995 For example, if the default ordering is by a non-unique ``name`` field,
996 then the changelist is sorted by ``name`` and ``pk``. This could
997 perform poorly if you have a lot of rows and don't have an index on
998 ``name`` and ``pk``.
999
1000 .. attribute:: ModelAdmin.paginator
1001
1002 The paginator class to be used for pagination. By default,
1003 :class:`django.core.paginator.Paginator` is used. If the custom paginator
1004 class doesn't have the same constructor interface as
1005 :class:`django.core.paginator.Paginator`, you will also need to
1006 provide an implementation for :meth:`ModelAdmin.get_paginator`.
1007
1008 .. attribute:: ModelAdmin.prepopulated_fields
1009
1010 Set ``prepopulated_fields`` to a dictionary mapping field names to the
1011 fields it should prepopulate from::
1012
1013 class ArticleAdmin(admin.ModelAdmin):
1014 prepopulated_fields = {"slug": ["title"]}
1015
1016 When set, the given fields will use a bit of JavaScript to populate from
1017 the fields assigned. The main use for this functionality is to
1018 automatically generate the value for ``SlugField`` fields from one or more
1019 other fields. The generated value is produced by concatenating the values
1020 of the source fields, and then by transforming that result into a valid
1021 slug (e.g. substituting dashes for spaces and lowercasing ASCII letters).
1022
1023 Prepopulated fields aren't modified by JavaScript after a value has been
1024 saved. It's usually undesired that slugs change (which would cause an
1025 object's URL to change if the slug is used in it).
1026
1027 ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,
1028 ``OneToOneField``, and ``ManyToManyField`` fields.
1029
1030 .. attribute:: ModelAdmin.preserve_filters
1031
1032 By default, applied filters are preserved on the list view after creating,
1033 editing, or deleting an object. You can have filters cleared by setting
1034 this attribute to ``False``.
1035
1036 .. attribute:: ModelAdmin.show_facets
1037
1038 Controls whether facet counts are displayed for filters in the admin
1039 changelist. Defaults to :attr:`.ShowFacets.ALLOW`.
1040
1041 When displayed, facet counts update in line with currently applied filters.
1042
1043 .. class:: ShowFacets
1044
1045 Enum of allowed values for :attr:`.ModelAdmin.show_facets`.
1046
1047 .. attribute:: ALWAYS
1048
1049 Always show facet counts.
1050
1051 .. attribute:: ALLOW
1052
1053 Show facet counts when the ``_facets`` query string parameter is
1054 provided.
1055
1056 .. attribute:: NEVER
1057
1058 Never show facet counts.
1059
1060 Set ``show_facets`` to the desired :class:`.ShowFacets` value. For example,
1061 to always show facet counts without needing to provide the query
1062 parameter::
1063
1064 from django.contrib import admin
1065
1066
1067 class MyModelAdmin(admin.ModelAdmin):
1068 ...
1069 # Have facets always shown for this model admin.
1070 show_facets = admin.ShowFacets.ALWAYS
1071
1072 .. admonition:: Performance considerations with facets
1073
1074 Enabling facet filters will increase the number of queries on the admin
1075 changelist page in line with the number of filters. These queries may
1076 cause performance problems, especially for large datasets. In these
1077 cases it may be appropriate to set ``show_facets`` to
1078 :attr:`.ShowFacets.NEVER` to disable faceting entirely.
1079
1080 .. attribute:: ModelAdmin.radio_fields
1081
1082 By default, Django's admin uses a select-box interface (<select>) for
1083 fields that are ``ForeignKey`` or have ``choices`` set. If a field is
1084 present in ``radio_fields``, Django will use a radio-button interface
1085 instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
1086
1087 class PersonAdmin(admin.ModelAdmin):
1088 radio_fields = {"group": admin.VERTICAL}
1089
1090 You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
1091 ``django.contrib.admin`` module.
1092
1093 Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
1094 ``choices`` set.
1095
1096 .. attribute:: ModelAdmin.autocomplete_fields
1097
1098 ``autocomplete_fields`` is a list of ``ForeignKey`` and/or
1099 ``ManyToManyField`` fields you would like to change to `Select2
1100 <https://select2.org/>`_ autocomplete inputs.
1101
1102 By default, the admin uses a select-box interface (``<select>``) for
1103 those fields. Sometimes you don't want to incur the overhead of selecting
1104 all the related instances to display in the dropdown.
1105
1106 The Select2 input looks similar to the default input but comes with a
1107 search feature that loads the options asynchronously. This is faster and
1108 more user-friendly if the related model has many instances.
1109
1110 You must define :attr:`~ModelAdmin.search_fields` on the related object's
1111 ``ModelAdmin`` because the autocomplete search uses it.
1112
1113 To avoid unauthorized data disclosure, users must have the ``view`` or
1114 ``change`` permission to the related object in order to use autocomplete.
1115
1116 Ordering and pagination of the results are controlled by the related
1117 ``ModelAdmin``'s :meth:`~ModelAdmin.get_ordering` and
1118 :meth:`~ModelAdmin.get_paginator` methods.
1119
1120 In the following example, ``ChoiceAdmin`` has an autocomplete field for the
1121 ``ForeignKey`` to the ``Question``. The results are filtered by the
1122 ``question_text`` field and ordered by the ``date_created`` field::
1123
1124 class QuestionAdmin(admin.ModelAdmin):
1125 ordering = ["date_created"]
1126 search_fields = ["question_text"]
1127
1128
1129 class ChoiceAdmin(admin.ModelAdmin):
1130 autocomplete_fields = ["question"]
1131
1132 .. admonition:: Performance considerations for large datasets
1133
1134 Ordering using :attr:`ModelAdmin.ordering` may cause performance
1135 problems as sorting on a large queryset will be slow.
1136
1137 Also, if your search fields include fields that aren't indexed by the
1138 database, you might encounter poor performance on extremely large
1139 tables.
1140
1141 For those cases, it's a good idea to write your own
1142 :func:`ModelAdmin.get_search_results` implementation using a
1143 full-text indexed search.
1144
1145 You may also want to change the ``Paginator`` on very large tables
1146 as the default paginator always performs a ``count()`` query.
1147 For example, you could override the default implementation of the
1148 ``Paginator.count`` property.
1149
1150 .. attribute:: ModelAdmin.raw_id_fields
1151
1152 By default, Django's admin uses a select-box interface (<select>) for
1153 fields that are ``ForeignKey``. Sometimes you don't want to incur the
1154 overhead of having to select all the related instances to display in the
1155 drop-down.
1156
1157 ``raw_id_fields`` is a list of fields you would like to change
1158 into an ``Input`` widget for either a ``ForeignKey`` or
1159 ``ManyToManyField``::
1160
1161 class ArticleAdmin(admin.ModelAdmin):
1162 raw_id_fields = ["newspaper"]
1163
1164 The ``raw_id_fields`` ``Input`` widget should contain a primary key if the
1165 field is a ``ForeignKey`` or a comma separated list of values if the field
1166 is a ``ManyToManyField``. The ``raw_id_fields`` widget shows a magnifying
1167 glass button next to the field which allows users to search for and select
1168 a value:
1169
1170 .. image:: _images/raw_id_fields.png
1171
1172 .. attribute:: ModelAdmin.readonly_fields
1173
1174 By default the admin shows all fields as editable. Any fields in this
1175 option (which should be a ``list`` or ``tuple``) will display its data
1176 as-is and non-editable; they are also excluded from the
1177 :class:`~django.forms.ModelForm` used for creating and editing. Note that
1178 when specifying :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets`
1179 the read-only fields must be present to be shown (they are ignored
1180 otherwise).
1181
1182 If ``readonly_fields`` is used without defining explicit ordering through
1183 :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be
1184 added last after all editable fields.
1185
1186 A read-only field can not only display data from a model's field, it can
1187 also display the output of a model's method or a method of the
1188 ``ModelAdmin`` class itself. This is very similar to the way
1189 :attr:`ModelAdmin.list_display` behaves. This provides a way to use the
1190 admin interface to provide feedback on the status of the objects being
1191 edited, for example::
1192
1193 from django.contrib import admin
1194 from django.utils.html import format_html_join
1195 from django.utils.safestring import mark_safe
1196
1197
1198 class PersonAdmin(admin.ModelAdmin):
1199 readonly_fields = ["address_report"]
1200
1201 # description functions like a model field's verbose_name
1202 @admin.display(description="Address")
1203 def address_report(self, instance):
1204 # assuming get_full_address() returns a list of strings
1205 # for each line of the address and you want to separate each
1206 # line by a linebreak
1207 return format_html_join(
1208 mark_safe("<br>"),
1209 "{}",
1210 ((line,) for line in instance.get_full_address()),
1211 ) or mark_safe("<span class='errors'>I can't determine this address.</span>")
1212
1213 .. attribute:: ModelAdmin.save_as
1214
1215 Set ``save_as`` to enable a "save as new" feature on admin change forms.
1216
1217 Normally, objects have three save options: "Save", "Save and continue
1218 editing", and "Save and add another". If ``save_as`` is ``True``, "Save
1219 and add another" will be replaced by a "Save as new" button that creates a
1220 new object (with a new ID) rather than updating the existing object.
1221
1222 By default, ``save_as`` is set to ``False``.
1223
1224 .. attribute:: ModelAdmin.save_as_continue
1225
1226 When :attr:`save_as=True <save_as>`, the default redirect after saving the
1227 new object is to the change view for that object. If you set
1228 ``save_as_continue=False``, the redirect will be to the changelist view.
1229
1230 By default, ``save_as_continue`` is set to ``True``.
1231
1232 .. attribute:: ModelAdmin.save_on_top
1233
1234 Set ``save_on_top`` to add save buttons across the top of your admin change
1235 forms.
1236
1237 Normally, the save buttons appear only at the bottom of the forms. If you
1238 set ``save_on_top``, the buttons will appear both on the top and the
1239 bottom.
1240
1241 By default, ``save_on_top`` is set to ``False``.
1242
1243 .. attribute:: ModelAdmin.search_fields
1244
1245 Set ``search_fields`` to enable a search box on the admin change list page.
1246 This should be set to a list of field names that will be searched whenever
1247 somebody submits a search query in that text box.
1248
1249 These fields should be some kind of text field, such as ``CharField`` or
1250 ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or
1251 ``ManyToManyField`` with the lookup API "follow" notation::
1252
1253 search_fields = ["foreign_key__related_fieldname"]
1254
1255 For example, if you have a blog entry with an author, the following
1256 definition would enable searching blog entries by the email address of the
1257 author::
1258
1259 search_fields = ["user__email"]
1260
1261 When somebody does a search in the admin search box, Django splits the
1262 search query into words and returns all objects that contain each of the
1263 words, case-insensitive (using the :lookup:`icontains` lookup), where each
1264 word must be in at least one of ``search_fields``. For example, if
1265 ``search_fields`` is set to ``['first_name', 'last_name']`` and a user
1266 searches for ``john lennon``, Django will do the equivalent of this SQL
1267 ``WHERE`` clause:
1268
1269 .. code-block:: sql
1270
1271 WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
1272 AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
1273
1274 The search query can contain quoted phrases with spaces. For example, if a
1275 user searches for ``"john winston"`` or ``'john winston'``, Django will do
1276 the equivalent of this SQL ``WHERE`` clause:
1277
1278 .. code-block:: sql
1279
1280 WHERE (first_name ILIKE '%john winston%' OR last_name ILIKE '%john winston%')
1281
1282 If you don't want to use ``icontains`` as the lookup, you can use any
1283 lookup by appending it the field. For example, you could use :lookup:`exact`
1284 by setting ``search_fields`` to ``['first_name__exact']``.
1285
1286 Some (older) shortcuts for specifying a field lookup are also available.
1287 You can prefix a field in ``search_fields`` with the following characters
1288 and it's equivalent to adding ``__<lookup>`` to the field:
1289
1290 ====== ====================
1291 Prefix Lookup
1292 ====== ====================
1293 ^ :lookup:`istartswith`
1294 = :lookup:`iexact`
1295 @ :lookup:`search`
1296 None :lookup:`icontains`
1297 ====== ====================
1298
1299 If you need to customize search you can use
1300 :meth:`ModelAdmin.get_search_results` to provide additional or alternate
1301 search behavior.
1302
1303 .. attribute:: ModelAdmin.search_help_text
1304
1305 Set ``search_help_text`` to specify a descriptive text for the search box
1306 which will be displayed below it.
1307
1308 .. attribute:: ModelAdmin.show_full_result_count
1309
1310 Set ``show_full_result_count`` to control whether the full count of objects
1311 should be displayed on a filtered admin page (e.g. ``99 results (103 total)``).
1312 If this option is set to ``False``, a text like ``99 results (Show all)``
1313 is displayed instead.
1314
1315 The default of ``show_full_result_count=True`` generates a query to perform
1316 a full count on the table which can be expensive if the table contains a
1317 large number of rows.
1318
1319 .. attribute:: ModelAdmin.sortable_by
1320
1321 By default, the change list page allows sorting by all model fields (and
1322 callables that use the ``ordering`` argument to the
1323 :func:`~django.contrib.admin.display` decorator or have the
1324 ``admin_order_field`` attribute) specified in :attr:`list_display`.
1325
1326 If you want to disable sorting for some columns, set ``sortable_by`` to
1327 a collection (e.g. ``list``, ``tuple``, or ``set``) of the subset of
1328 :attr:`list_display` that you want to be sortable. An empty collection
1329 disables sorting for all columns.
1330
1331 If you need to specify this list dynamically, implement a
1332 :meth:`~ModelAdmin.get_sortable_by` method instead.
1333
1334 .. attribute:: ModelAdmin.view_on_site
1335
1336 Set ``view_on_site`` to control whether or not to display the "View on site" link.
1337 This link should bring you to a URL where you can display the saved object.
1338
1339 This value can be either a boolean flag or a callable. If ``True`` (the
1340 default), the object's :meth:`~django.db.models.Model.get_absolute_url`
1341 method will be used to generate the url.
1342
1343 If your model has a :meth:`~django.db.models.Model.get_absolute_url` method
1344 but you don't want the "View on site" button to appear, you only need to set
1345 ``view_on_site`` to ``False``::
1346
1347 from django.contrib import admin
1348
1349
1350 class PersonAdmin(admin.ModelAdmin):
1351 view_on_site = False
1352
1353 In case it is a callable, it accepts the model instance as a parameter.
1354 For example::
1355
1356 from django.contrib import admin
1357 from django.urls import reverse
1358
1359
1360 class PersonAdmin(admin.ModelAdmin):
1361 def view_on_site(self, obj):
1362 url = reverse("person-detail", kwargs={"slug": obj.slug})
1363 return "https://example.com" + url
1364
1365 Custom template options
1366 ~~~~~~~~~~~~~~~~~~~~~~~
1367
1368 The :ref:`admin-overriding-templates` section describes how to override or extend
1369 the default admin templates. Use the following options to override the default
1370 templates used by the :class:`ModelAdmin` views:
1371
1372 .. attribute:: ModelAdmin.add_form_template
1373
1374 Path to a custom template, used by :meth:`add_view`.
1375
1376 .. attribute:: ModelAdmin.change_form_template
1377
1378 Path to a custom template, used by :meth:`change_view`.
1379
1380 .. attribute:: ModelAdmin.change_list_template
1381
1382 Path to a custom template, used by :meth:`changelist_view`.
1383
1384 .. attribute:: ModelAdmin.delete_confirmation_template
1385
1386 Path to a custom template, used by :meth:`delete_view` for displaying a
1387 confirmation page when deleting one or more objects.
1388
1389 .. attribute:: ModelAdmin.delete_selected_confirmation_template
1390
1391 Path to a custom template, used by the ``delete_selected`` action method
1392 for displaying a confirmation page when deleting one or more objects. See
1393 the :doc:`actions documentation</ref/contrib/admin/actions>`.
1394
1395 .. attribute:: ModelAdmin.object_history_template
1396
1397 Path to a custom template, used by :meth:`history_view`.
1398
1399 .. attribute:: ModelAdmin.popup_response_template
1400
1401 Path to a custom template, used by :meth:`response_add`,
1402 :meth:`response_change`, and :meth:`response_delete`.
1403
1404 .. _model-admin-methods:
1405
1406 ``ModelAdmin`` methods
1407 ----------------------
1408
1409 .. warning::
1410
1411 When overriding :meth:`ModelAdmin.save_model` and
1412 :meth:`ModelAdmin.delete_model`, your code must save/delete the
1413 object. They aren't meant for veto purposes, rather they allow you to
1414 perform extra operations.
1415
1416 .. method:: ModelAdmin.save_model(request, obj, form, change)
1417
1418 The ``save_model`` method is given the ``HttpRequest``, a model instance,
1419 a ``ModelForm`` instance, and a boolean value based on whether it is adding
1420 or changing the object. Overriding this method allows doing pre- or
1421 post-save operations. Call ``super().save_model()`` to save the object
1422 using :meth:`.Model.save`.
1423
1424 For example to attach ``request.user`` to the object prior to saving::
1425
1426 from django.contrib import admin
1427
1428
1429 class ArticleAdmin(admin.ModelAdmin):
1430 def save_model(self, request, obj, form, change):
1431 obj.user = request.user
1432 super().save_model(request, obj, form, change)
1433
1434 .. method:: ModelAdmin.delete_model(request, obj)
1435
1436 The ``delete_model`` method is given the ``HttpRequest`` and a model
1437 instance. Overriding this method allows doing pre- or post-delete
1438 operations. Call ``super().delete_model()`` to delete the object using
1439 :meth:`.Model.delete`.
1440
1441 .. method:: ModelAdmin.delete_queryset(request, queryset)
1442
1443 The ``delete_queryset()`` method is given the ``HttpRequest`` and a
1444 ``QuerySet`` of objects to be deleted. Override this method to customize
1445 the deletion process for the "delete selected objects" :doc:`action
1446 <actions>`.
1447
1448 .. method:: ModelAdmin.save_formset(request, form, formset, change)
1449
1450 The ``save_formset`` method is given the ``HttpRequest``, the parent
1451 ``ModelForm`` instance and a boolean value based on whether it is adding or
1452 changing the parent object.
1453
1454 For example, to attach ``request.user`` to each changed formset
1455 model instance::
1456
1457 class ArticleAdmin(admin.ModelAdmin):
1458 def save_formset(self, request, form, formset, change):
1459 instances = formset.save(commit=False)
1460 for obj in formset.deleted_objects:
1461 obj.delete()
1462 for instance in instances:
1463 instance.user = request.user
1464 instance.save()
1465 formset.save_m2m()
1466
1467 See also :ref:`saving-objects-in-the-formset`.
1468
1469 .. warning::
1470
1471 All hooks that return a ``ModelAdmin`` property return the property itself
1472 rather than a copy of its value. Dynamically modifying the value can lead
1473 to surprising results.
1474
1475 Let's take :meth:`ModelAdmin.get_readonly_fields` as an example::
1476
1477 class PersonAdmin(admin.ModelAdmin):
1478 readonly_fields = ["name"]
1479
1480 def get_readonly_fields(self, request, obj=None):
1481 readonly = super().get_readonly_fields(request, obj)
1482 if not request.user.is_superuser:
1483 readonly.append("age") # Edits the class attribute.
1484 return readonly
1485
1486 This results in ``readonly_fields`` becoming
1487 ``["name", "age", "age", ...]``, even for a superuser, as ``"age"`` is added
1488 each time non-superuser visits the page.
1489
1490 .. method:: ModelAdmin.get_ordering(request)
1491
1492 The ``get_ordering`` method takes a ``request`` as parameter and
1493 is expected to return a ``list`` or ``tuple`` for ordering similar
1494 to the :attr:`ordering` attribute. For example::
1495
1496 class PersonAdmin(admin.ModelAdmin):
1497 def get_ordering(self, request):
1498 if request.user.is_superuser:
1499 return ["name", "rank"]
1500 else:
1501 return ["name"]
1502
1503 .. method:: ModelAdmin.get_search_results(request, queryset, search_term)
1504
1505 The ``get_search_results`` method modifies the list of objects displayed
1506 into those that match the provided search term. It accepts the request, a
1507 queryset that applies the current filters, and the user-provided search term.
1508 It returns a tuple containing a queryset modified to implement the search, and
1509 a boolean indicating if the results may contain duplicates.
1510
1511 The default implementation searches the fields named in :attr:`ModelAdmin.search_fields`.
1512
1513 This method may be overridden with your own custom search method. For
1514 example, you might wish to search by an integer field, or use an external
1515 tool such as `Solr`_ or `Haystack`_. You must establish if the queryset
1516 changes implemented by your search method may introduce duplicates into the
1517 results, and return ``True`` in the second element of the return value.
1518
1519 For example, to search by ``name`` and ``age``, you could use::
1520
1521 class PersonAdmin(admin.ModelAdmin):
1522 list_display = ["name", "age"]
1523 search_fields = ["name"]
1524
1525 def get_search_results(self, request, queryset, search_term):
1526 queryset, may_have_duplicates = super().get_search_results(
1527 request,
1528 queryset,
1529 search_term,
1530 )
1531 try:
1532 search_term_as_int = int(search_term)
1533 except ValueError:
1534 pass
1535 else:
1536 queryset |= self.model.objects.filter(age=search_term_as_int)
1537 return queryset, may_have_duplicates
1538
1539 This implementation is more efficient than ``search_fields =
1540 ('name', '=age')`` which results in a string comparison for the numeric
1541 field, for example ``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')``
1542 on PostgreSQL.
1543
1544 .. _Solr: https://solr.apache.org
1545 .. _Haystack: https://haystacksearch.org
1546
1547 .. method:: ModelAdmin.save_related(request, form, formsets, change)
1548
1549 The ``save_related`` method is given the ``HttpRequest``, the parent
1550 ``ModelForm`` instance, the list of inline formsets and a boolean value
1551 based on whether the parent is being added or changed. Here you can do any
1552 pre- or post-save operations for objects related to the parent. Note
1553 that at this point the parent object and its form have already been saved.
1554
1555 .. method:: ModelAdmin.get_autocomplete_fields(request)
1556
1557 The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and is
1558 expected to return a ``list`` or ``tuple`` of field names that will be
1559 displayed with an autocomplete widget as described above in the
1560 :attr:`ModelAdmin.autocomplete_fields` section.
1561
1562 .. method:: ModelAdmin.get_readonly_fields(request, obj=None)
1563
1564 The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
1565 ``obj`` being edited (or ``None`` on an add form) and is expected to return
1566 a ``list`` or ``tuple`` of field names that will be displayed as read-only,
1567 as described above in the :attr:`ModelAdmin.readonly_fields` section.
1568
1569 .. method:: ModelAdmin.get_prepopulated_fields(request, obj=None)
1570
1571 The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the
1572 ``obj`` being edited (or ``None`` on an add form) and is expected to return
1573 a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`
1574 section.
1575
1576 .. method:: ModelAdmin.get_list_display(request)
1577
1578 The ``get_list_display`` method is given the ``HttpRequest`` and is
1579 expected to return a ``list`` or ``tuple`` of field names that will be
1580 displayed on the changelist view as described above in the
1581 :attr:`ModelAdmin.list_display` section.
1582
1583 .. method:: ModelAdmin.get_list_display_links(request, list_display)
1584
1585 The ``get_list_display_links`` method is given the ``HttpRequest`` and
1586 the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`.
1587 It is expected to return either ``None`` or a ``list`` or ``tuple`` of field
1588 names on the changelist that will be linked to the change view, as described
1589 in the :attr:`ModelAdmin.list_display_links` section.
1590
1591 .. method:: ModelAdmin.get_exclude(request, obj=None)
1592
1593 The ``get_exclude`` method is given the ``HttpRequest`` and the ``obj``
1594 being edited (or ``None`` on an add form) and is expected to return a list
1595 of fields, as described in :attr:`ModelAdmin.exclude`.
1596
1597 .. method:: ModelAdmin.get_fields(request, obj=None)
1598
1599 The ``get_fields`` method is given the ``HttpRequest`` and the ``obj``
1600 being edited (or ``None`` on an add form) and is expected to return a list
1601 of fields, as described above in the :attr:`ModelAdmin.fields` section.
1602
1603 .. method:: ModelAdmin.get_fieldsets(request, obj=None)
1604
1605 The ``get_fieldsets`` method is given the ``HttpRequest`` and the ``obj``
1606 being edited (or ``None`` on an add form) and is expected to return a list
1607 of 2-tuples, in which each 2-tuple represents a ``<fieldset>`` on the
1608 admin form page, as described above in the :attr:`ModelAdmin.fieldsets` section.
1609
1610 .. method:: ModelAdmin.get_list_filter(request)
1611
1612 The ``get_list_filter`` method is given the ``HttpRequest`` and is expected
1613 to return the same kind of sequence type as for the
1614 :attr:`~ModelAdmin.list_filter` attribute.
1615
1616 .. method:: ModelAdmin.get_list_select_related(request)
1617
1618 The ``get_list_select_related`` method is given the ``HttpRequest`` and
1619 should return a boolean or list as :attr:`ModelAdmin.list_select_related`
1620 does.
1621
1622 .. method:: ModelAdmin.get_search_fields(request)
1623
1624 The ``get_search_fields`` method is given the ``HttpRequest`` and is expected
1625 to return the same kind of sequence type as for the
1626 :attr:`~ModelAdmin.search_fields` attribute.
1627
1628 .. method:: ModelAdmin.get_sortable_by(request)
1629
1630 The ``get_sortable_by()`` method is passed the ``HttpRequest`` and is
1631 expected to return a collection (e.g. ``list``, ``tuple``, or ``set``) of
1632 field names that will be sortable in the change list page.
1633
1634 Its default implementation returns :attr:`sortable_by` if it's set,
1635 otherwise it defers to :meth:`get_list_display`.
1636
1637 For example, to prevent one or more columns from being sortable::
1638
1639 class PersonAdmin(admin.ModelAdmin):
1640 def get_sortable_by(self, request):
1641 return {*self.get_list_display(request)} - {"rank"}
1642
1643 .. method:: ModelAdmin.get_inline_instances(request, obj=None)
1644
1645 The ``get_inline_instances`` method is given the ``HttpRequest`` and the
1646 ``obj`` being edited (or ``None`` on an add form) and is expected to return
1647 a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`
1648 objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin`
1649 section. For example, the following would return inlines without the default
1650 filtering based on add, change, delete, and view permissions::
1651
1652 class MyModelAdmin(admin.ModelAdmin):
1653 inlines = [MyInline]
1654
1655 def get_inline_instances(self, request, obj=None):
1656 return [inline(self.model, self.admin_site) for inline in self.inlines]
1657
1658 If you override this method, make sure that the returned inlines are
1659 instances of the classes defined in :attr:`inlines` or you might encounter
1660 a "Bad Request" error when adding related objects.
1661
1662 .. method:: ModelAdmin.get_inlines(request, obj)
1663
1664 The ``get_inlines`` method is given the ``HttpRequest`` and the
1665 ``obj`` being edited (or ``None`` on an add form) and is expected to return
1666 an iterable of inlines. You can override this method to dynamically add
1667 inlines based on the request or model instance instead of specifying them
1668 in :attr:`ModelAdmin.inlines`.
1669
1670 .. method:: ModelAdmin.get_urls()
1671
1672 The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
1673 that ModelAdmin in the same way as a URLconf. Therefore you can extend
1674 them as documented in :doc:`/topics/http/urls`, using the
1675 ``AdminSite.admin_view()`` wrapper on your views::
1676
1677 from django.contrib import admin
1678 from django.template.response import TemplateResponse
1679 from django.urls import path
1680
1681
1682 class MyModelAdmin(admin.ModelAdmin):
1683 def get_urls(self):
1684 urls = super().get_urls()
1685 my_urls = [path("my_view/", self.admin_site.admin_view(self.my_view))]
1686 return my_urls + urls
1687
1688 def my_view(self, request):
1689 # ...
1690 context = dict(
1691 # Include common variables for rendering the admin template.
1692 self.admin_site.each_context(request),
1693 # Anything else you want in the context...
1694 key=value,
1695 )
1696 return TemplateResponse(request, "sometemplate.html", context)
1697
1698 If you want to use the admin layout, extend from ``admin/base_site.html``:
1699
1700 .. code-block:: html+django
1701
1702 {% extends "admin/base_site.html" %}
1703 {% block content %}
1704 ...
1705 {% endblock %}
1706
1707 .. note::
1708
1709 Notice how the ``self.my_view`` function is wrapped in
1710 ``self.admin_site.admin_view``. This is important, since it ensures two
1711 things:
1712
1713 #. Permission checks are run, ensuring only active staff users can
1714 access the view.
1715 #. The :func:`django.views.decorators.cache.never_cache` decorator is
1716 applied to prevent caching, ensuring the returned information is
1717 up-to-date.
1718
1719 .. note::
1720
1721 Notice that the custom patterns are included *before* the regular admin
1722 URLs: the admin URL patterns are very permissive and will match nearly
1723 anything, so you'll usually want to prepend your custom URLs to the
1724 built-in ones.
1725
1726 In this example, ``my_view`` will be accessed at
1727 ``/admin/myapp/mymodel/my_view/`` (assuming the admin URLs are included
1728 at ``/admin/``.)
1729
1730 If the page is cacheable, but you still want the permission check to be
1731 performed, you can pass a ``cacheable=True`` argument to
1732 ``AdminSite.admin_view()``::
1733
1734 path("my_view/", self.admin_site.admin_view(self.my_view, cacheable=True))
1735
1736 ``ModelAdmin`` views have ``model_admin`` attributes. Other
1737 ``AdminSite`` views have ``admin_site`` attributes.
1738
1739 .. method:: ModelAdmin.get_form(request, obj=None, **kwargs)
1740
1741 Returns a :class:`~django.forms.ModelForm` class for use in the admin add
1742 and change views, see :meth:`add_view` and :meth:`change_view`.
1743
1744 The base implementation uses :func:`~django.forms.models.modelform_factory`
1745 to subclass :attr:`~form`, modified by attributes such as :attr:`~fields`
1746 and :attr:`~exclude`. So, for example, if you wanted to offer additional
1747 fields to superusers, you could swap in a different base form like so::
1748
1749 class MyModelAdmin(admin.ModelAdmin):
1750 def get_form(self, request, obj=None, **kwargs):
1751 if request.user.is_superuser:
1752 kwargs["form"] = MySuperuserForm
1753 return super().get_form(request, obj, **kwargs)
1754
1755 You may also return a custom :class:`~django.forms.ModelForm` class
1756 directly.
1757
1758 .. method:: ModelAdmin.get_formsets_with_inlines(request, obj=None)
1759
1760 Yields (``FormSet``, :class:`InlineModelAdmin`) pairs for use in admin add
1761 and change views.
1762
1763 For example if you wanted to display a particular inline only in the change
1764 view, you could override ``get_formsets_with_inlines`` as follows::
1765
1766 class MyModelAdmin(admin.ModelAdmin):
1767 inlines = [MyInline, SomeOtherInline]
1768
1769 def get_formsets_with_inlines(self, request, obj=None):
1770 for inline in self.get_inline_instances(request, obj):
1771 # hide MyInline in the add view
1772 if not isinstance(inline, MyInline) or obj is not None:
1773 yield inline.get_formset(request, obj), inline
1774
1775 .. method:: ModelAdmin.formfield_for_foreignkey(db_field, request, **kwargs)
1776
1777 The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to
1778 override the default formfield for a foreign keys field. For example, to
1779 return a subset of objects for this foreign key field based on the user::
1780
1781 class MyModelAdmin(admin.ModelAdmin):
1782 def formfield_for_foreignkey(self, db_field, request, **kwargs):
1783 if db_field.name == "car":
1784 kwargs["queryset"] = Car.objects.filter(owner=request.user)
1785 return super().formfield_for_foreignkey(db_field, request, **kwargs)
1786
1787 This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
1788 field to only display the cars owned by the ``User`` instance.
1789
1790 For more complex filters, you can use ``ModelForm.__init__()`` method to
1791 filter based on an ``instance`` of your model (see
1792 :ref:`fields-which-handle-relationships`). For example::
1793
1794 class CountryAdminForm(forms.ModelForm):
1795 def __init__(self, *args, **kwargs):
1796 super().__init__(*args, **kwargs)
1797 self.fields["capital"].queryset = self.instance.cities.all()
1798
1799
1800 class CountryAdmin(admin.ModelAdmin):
1801 form = CountryAdminForm
1802
1803 .. method:: ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)
1804
1805 Like the ``formfield_for_foreignkey`` method, the
1806 ``formfield_for_manytomany`` method can be overridden to change the
1807 default formfield for a many to many field. For example, if an owner can
1808 own multiple cars and cars can belong to multiple owners -- a many to
1809 many relationship -- you could filter the ``Car`` foreign key field to
1810 only display the cars owned by the ``User``::
1811
1812 class MyModelAdmin(admin.ModelAdmin):
1813 def formfield_for_manytomany(self, db_field, request, **kwargs):
1814 if db_field.name == "cars":
1815 kwargs["queryset"] = Car.objects.filter(owner=request.user)
1816 return super().formfield_for_manytomany(db_field, request, **kwargs)
1817
1818 .. method:: ModelAdmin.formfield_for_choice_field(db_field, request, **kwargs)
1819
1820 Like the ``formfield_for_foreignkey`` and ``formfield_for_manytomany``
1821 methods, the ``formfield_for_choice_field`` method can be overridden to
1822 change the default formfield for a field that has declared choices. For
1823 example, if the choices available to a superuser should be different than
1824 those available to regular staff, you could proceed as follows::
1825
1826 class MyModelAdmin(admin.ModelAdmin):
1827 def formfield_for_choice_field(self, db_field, request, **kwargs):
1828 if db_field.name == "status":
1829 kwargs["choices"] = [
1830 ("accepted", "Accepted"),
1831 ("denied", "Denied"),
1832 ]
1833 if request.user.is_superuser:
1834 kwargs["choices"].append(("ready", "Ready for deployment"))
1835 return super().formfield_for_choice_field(db_field, request, **kwargs)
1836
1837 .. admonition:: ``choices`` limitations
1838
1839 Any ``choices`` attribute set on the formfield will be limited to the
1840 form field only. If the corresponding field on the model has choices
1841 set, the choices provided to the form must be a valid subset of those
1842 choices, otherwise the form submission will fail with
1843 a :exc:`~django.core.exceptions.ValidationError` when the model itself
1844 is validated before saving.
1845
1846 .. method:: ModelAdmin.get_changelist(request, **kwargs)
1847
1848 Returns the ``Changelist`` class to be used for listing. By default,
1849 ``django.contrib.admin.views.main.ChangeList`` is used. By inheriting this
1850 class you can change the behavior of the listing.
1851
1852 .. method:: ModelAdmin.get_changelist_form(request, **kwargs)
1853
1854 Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``
1855 on the changelist page. To use a custom form, for example::
1856
1857 from django import forms
1858
1859
1860 class MyForm(forms.ModelForm):
1861 pass
1862
1863
1864 class MyModelAdmin(admin.ModelAdmin):
1865 def get_changelist_form(self, request, **kwargs):
1866 return MyForm
1867
1868 .. admonition:: Omit the ``Meta.model`` attribute
1869
1870 If you define the ``Meta.model`` attribute on a
1871 :class:`~django.forms.ModelForm`, you must also define the
1872 ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
1873 ``ModelAdmin`` ignores this value, overriding it with the
1874 :attr:`ModelAdmin.list_editable` attribute. The easiest solution is to
1875 omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide the
1876 correct model to use.
1877
1878 .. method:: ModelAdmin.get_changelist_formset(request, **kwargs)
1879
1880 Returns a :ref:`ModelFormSet <model-formsets>` class for use on the
1881 changelist page if :attr:`~ModelAdmin.list_editable` is used. To use a
1882 custom formset, for example::
1883
1884 from django.forms import BaseModelFormSet
1885
1886
1887 class MyAdminFormSet(BaseModelFormSet):
1888 pass
1889
1890
1891 class MyModelAdmin(admin.ModelAdmin):
1892 def get_changelist_formset(self, request, **kwargs):
1893 kwargs["formset"] = MyAdminFormSet
1894 return super().get_changelist_formset(request, **kwargs)
1895
1896 .. method:: ModelAdmin.lookup_allowed(lookup, value, request)
1897
1898 The objects in the changelist page can be filtered with lookups from the
1899 URL's query string. This is how :attr:`list_filter` works, for example. The
1900 lookups are similar to what's used in :meth:`.QuerySet.filter` (e.g.
1901 ``[email protected]``). Since the lookups in the query string
1902 can be manipulated by the user, they must be sanitized to prevent
1903 unauthorized data exposure.
1904
1905 The ``lookup_allowed()`` method is given a lookup path from the query string
1906 (e.g. ``'user__email'``), the corresponding value
1907 (e.g. ``'[email protected]'``), and the request, and returns a boolean
1908 indicating whether filtering the changelist's ``QuerySet`` using the
1909 parameters is permitted. If ``lookup_allowed()`` returns ``False``,
1910 ``DisallowedModelAdminLookup``
1911 (subclass of :exc:`~django.core.exceptions.SuspiciousOperation`) is raised.
1912
1913 By default, ``lookup_allowed()`` allows access to a model's local fields,
1914 field paths used in :attr:`~ModelAdmin.list_filter` (but not paths from
1915 :meth:`~ModelAdmin.get_list_filter`), and lookups required for
1916 :attr:`~django.db.models.ForeignKey.limit_choices_to` to function
1917 correctly in :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields`.
1918
1919 Override this method to customize the lookups permitted for your
1920 :class:`~django.contrib.admin.ModelAdmin` subclass.
1921
1922 .. method:: ModelAdmin.has_view_permission(request, obj=None)
1923
1924 Should return ``True`` if viewing ``obj`` is permitted, ``False`` otherwise.
1925 If obj is ``None``, should return ``True`` or ``False`` to indicate whether
1926 viewing of objects of this type is permitted in general (e.g., ``False``
1927 will be interpreted as meaning that the current user is not permitted to
1928 view any object of this type).
1929
1930 The default implementation returns ``True`` if the user has either the
1931 "change" or "view" permission.
1932
1933 .. method:: ModelAdmin.has_add_permission(request)
1934
1935 Should return ``True`` if adding an object is permitted, ``False``
1936 otherwise.
1937
1938 .. method:: ModelAdmin.has_change_permission(request, obj=None)
1939
1940 Should return ``True`` if editing ``obj`` is permitted, ``False``
1941 otherwise. If ``obj`` is ``None``, should return ``True`` or ``False`` to
1942 indicate whether editing of objects of this type is permitted in general
1943 (e.g., ``False`` will be interpreted as meaning that the current user is
1944 not permitted to edit any object of this type).
1945
1946 .. method:: ModelAdmin.has_delete_permission(request, obj=None)
1947
1948 Should return ``True`` if deleting ``obj`` is permitted, ``False``
1949 otherwise. If ``obj`` is ``None``, should return ``True`` or ``False`` to
1950 indicate whether deleting objects of this type is permitted in general
1951 (e.g., ``False`` will be interpreted as meaning that the current user is
1952 not permitted to delete any object of this type).
1953
1954 .. method:: ModelAdmin.has_module_permission(request)
1955
1956 Should return ``True`` if displaying the module on the admin index page and
1957 accessing the module's index page is permitted, ``False`` otherwise.
1958 Uses :meth:`User.has_module_perms()
1959 <django.contrib.auth.models.User.has_module_perms>` by default. Overriding
1960 it does not restrict access to the view, add, change, or delete views,
1961 :meth:`~ModelAdmin.has_view_permission`,
1962 :meth:`~ModelAdmin.has_add_permission`,
1963 :meth:`~ModelAdmin.has_change_permission`, and
1964 :meth:`~ModelAdmin.has_delete_permission` should be used for that.
1965
1966 .. method:: ModelAdmin.get_queryset(request)
1967
1968 The ``get_queryset`` method on a ``ModelAdmin`` returns a
1969 :class:`~django.db.models.query.QuerySet` of all model instances that
1970 can be edited by the admin site. One use case for overriding this method
1971 is to show objects owned by the logged-in user::
1972
1973 class MyModelAdmin(admin.ModelAdmin):
1974 def get_queryset(self, request):
1975 qs = super().get_queryset(request)
1976 if request.user.is_superuser:
1977 return qs
1978 return qs.filter(author=request.user)
1979
1980 .. method:: ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)
1981
1982 Sends a message to the user using the :mod:`django.contrib.messages`
1983 backend. See the :ref:`custom ModelAdmin example <custom-admin-action>`.
1984
1985 Keyword arguments allow you to change the message level, add extra CSS
1986 tags, or fail silently if the ``contrib.messages`` framework is not
1987 installed. These keyword arguments match those for
1988 :func:`django.contrib.messages.add_message`, see that function's
1989 documentation for more details. One difference is that the level may be
1990 passed as a string label in addition to integer/constant.
1991
1992 .. method:: ModelAdmin.get_paginator(request, queryset, per_page, orphans=0, allow_empty_first_page=True)
1993
1994 Returns an instance of the paginator to use for this view. By default,
1995 instantiates an instance of :attr:`paginator`.
1996
1997 .. method:: ModelAdmin.response_add(request, obj, post_url_continue=None)
1998
1999 Determines the :class:`~django.http.HttpResponse` for the
2000 :meth:`add_view` stage.
2001
2002 ``response_add`` is called after the admin form is submitted and
2003 just after the object and all the related instances have
2004 been created and saved. You can override it to change the default behavior
2005 after the object has been created.
2006
2007 .. method:: ModelAdmin.response_change(request, obj)
2008
2009 Determines the :class:`~django.http.HttpResponse` for the
2010 :meth:`change_view` stage.
2011
2012 ``response_change`` is called after the admin form is submitted and
2013 just after the object and all the related instances have
2014 been saved. You can override it to change the default
2015 behavior after the object has been changed.
2016
2017 .. method:: ModelAdmin.response_delete(request, obj_display, obj_id)
2018
2019 Determines the :class:`~django.http.HttpResponse` for the
2020 :meth:`delete_view` stage.
2021
2022 ``response_delete`` is called after the object has been
2023 deleted. You can override it to change the default
2024 behavior after the object has been deleted.
2025
2026 ``obj_display`` is a string with the name of the deleted
2027 object.
2028
2029 ``obj_id`` is the serialized identifier used to retrieve the object to be
2030 deleted.
2031
2032 .. method:: ModelAdmin.get_formset_kwargs(request, obj, inline, prefix)
2033
2034 A hook for customizing the keyword arguments passed to the constructor of a
2035 formset. For example, to pass ``request`` to formset forms::
2036
2037 class MyModelAdmin(admin.ModelAdmin):
2038 def get_formset_kwargs(self, request, obj, inline, prefix):
2039 return {
2040 **super().get_formset_kwargs(request, obj, inline, prefix),
2041 "form_kwargs": {"request": request},
2042 }
2043
2044 You can also use it to set ``initial`` for formset forms.
2045
2046 .. method:: ModelAdmin.get_changeform_initial_data(request)
2047
2048 A hook for the initial data on admin change forms. By default, fields are
2049 given initial values from ``GET`` parameters. For instance,
2050 ``?name=initial_value`` will set the ``name`` field's initial value to be
2051 ``initial_value``.
2052
2053 This method should return a dictionary in the form
2054 ``{'fieldname': 'fieldval'}``::
2055
2056 def get_changeform_initial_data(self, request):
2057 return {"name": "custom_initial_value"}
2058
2059 .. method:: ModelAdmin.get_deleted_objects(objs, request)
2060
2061 A hook for customizing the deletion process of the :meth:`delete_view` and
2062 the "delete selected" :doc:`action <actions>`.
2063
2064 The ``objs`` argument is a homogeneous iterable of objects (a ``QuerySet``
2065 or a list of model instances) to be deleted, and ``request`` is the
2066 :class:`~django.http.HttpRequest`.
2067
2068 This method must return a 4-tuple of
2069 ``(deleted_objects, model_count, perms_needed, protected)``.
2070
2071 ``deleted_objects`` is a list of strings representing all the objects that
2072 will be deleted. If there are any related objects to be deleted, the list
2073 is nested and includes those related objects. The list is formatted in the
2074 template using the :tfilter:`unordered_list` filter.
2075
2076 ``model_count`` is a dictionary mapping each model's
2077 :attr:`~django.db.models.Options.verbose_name_plural` to the number of
2078 objects that will be deleted.
2079
2080 ``perms_needed`` is a set of :attr:`~django.db.models.Options.verbose_name`\s
2081 of the models that the user doesn't have permission to delete.
2082
2083 ``protected`` is a list of strings representing of all the protected
2084 related objects that can't be deleted. The list is displayed in the
2085 template.
2086
2087 Other methods
2088 ~~~~~~~~~~~~~
2089
2090 .. method:: ModelAdmin.add_view(request, form_url='', extra_context=None)
2091
2092 Django view for the model instance addition page. See note below.
2093
2094 .. method:: ModelAdmin.change_view(request, object_id, form_url='', extra_context=None)
2095
2096 Django view for the model instance editing page. See note below.
2097
2098 .. method:: ModelAdmin.changelist_view(request, extra_context=None)
2099
2100 Django view for the model instances change list/actions page. See note
2101 below.
2102
2103 .. method:: ModelAdmin.delete_view(request, object_id, extra_context=None)
2104
2105 Django view for the model instance(s) deletion confirmation page. See note
2106 below.
2107
2108 .. method:: ModelAdmin.history_view(request, object_id, extra_context=None)
2109
2110 Django view for the page that shows the modification history for a given
2111 model instance.
2112
2113 Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
2114 these five methods are in reality designed to be invoked as Django views from
2115 the admin application URL dispatching handler to render the pages that deal
2116 with model instances CRUD operations. As a result, completely overriding these
2117 methods will significantly change the behavior of the admin application.
2118
2119 One common reason for overriding these methods is to augment the context data
2120 that is provided to the template that renders the view. In the following
2121 example, the change view is overridden so that the rendered template is
2122 provided some extra mapping data that would not otherwise be available::
2123
2124 class MyModelAdmin(admin.ModelAdmin):
2125 # A template for a very customized change view:
2126 change_form_template = "admin/myapp/extras/openstreetmap_change_form.html"
2127
2128 def get_osm_info(self):
2129 # ...
2130 pass
2131
2132 def change_view(self, request, object_id, form_url="", extra_context=None):
2133 extra_context = extra_context or {}
2134 extra_context["osm_data"] = self.get_osm_info()
2135 return super().change_view(
2136 request,
2137 object_id,
2138 form_url,
2139 extra_context=extra_context,
2140 )
2141
2142 These views return :class:`~django.template.response.TemplateResponse`
2143 instances which allow you to easily customize the response data before
2144 rendering. For more details, see the :doc:`TemplateResponse documentation
2145 </ref/template-response>`.
2146
2147 .. _modeladmin-asset-definitions:
2148
2149 ``ModelAdmin`` asset definitions
2150 --------------------------------
2151
2152 There are times where you would like add a bit of CSS and/or JavaScript to
2153 the add/change views. This can be accomplished by using a ``Media`` inner class
2154 on your ``ModelAdmin``::
2155
2156 class ArticleAdmin(admin.ModelAdmin):
2157 class Media:
2158 css = {
2159 "all": ["my_styles.css"],
2160 }
2161 js = ["my_code.js"]
2162
2163 The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends
2164 :setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is
2165 ``None``) to any asset paths. The same rules apply as :ref:`regular asset
2166 definitions on forms <form-asset-paths>`.
2167
2168 .. _contrib-admin-jquery:
2169
2170 jQuery
2171 ~~~~~~
2172
2173 Django admin JavaScript makes use of the `jQuery`_ library.
2174
2175 To avoid conflicts with user-supplied scripts or libraries, Django's jQuery
2176 (version 3.7.1) is namespaced as ``django.jQuery``. If you want to use jQuery
2177 in your own admin JavaScript without including a second copy, you can use the
2178 ``django.jQuery`` object on changelist and add/edit views. Also, your own admin
2179 forms or widgets depending on ``django.jQuery`` must specify
2180 ``js=['admin/js/jquery.init.js', …]`` when :ref:`declaring form media assets
2181 <assets-as-a-static-definition>`.
2182
2183 The :class:`ModelAdmin` class requires jQuery by default, so there is no need
2184 to add jQuery to your ``ModelAdmin``’s list of media resources unless you have
2185 a specific need. For example, if you require the jQuery library to be in the
2186 global namespace (for example when using third-party jQuery plugins) or if you
2187 need a newer version of jQuery, you will have to include your own copy.
2188
2189 Django provides both uncompressed and 'minified' versions of jQuery, as
2190 ``jquery.js`` and ``jquery.min.js`` respectively.
2191
2192 :class:`ModelAdmin` and :class:`InlineModelAdmin` have a ``media`` property
2193 that returns a list of ``Media`` objects which store paths to the JavaScript
2194 files for the forms and/or formsets. If :setting:`DEBUG` is ``True`` it will
2195 return the uncompressed versions of the various JavaScript files, including
2196 ``jquery.js``; if not, it will return the 'minified' versions.
2197
2198 .. _jQuery: https://jquery.com
2199
2200 .. _admin-custom-validation:
2201
2202 Adding custom validation to the admin
2203 -------------------------------------
2204
2205 You can also add custom validation of data in the admin. The automatic admin
2206 interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you
2207 the ability to define your own form::
2208
2209 class ArticleAdmin(admin.ModelAdmin):
2210 form = MyArticleAdminForm
2211
2212 ``MyArticleAdminForm`` can be defined anywhere as long as you import where
2213 needed. Now within your form you can add your own custom validation for
2214 any field::
2215
2216 class MyArticleAdminForm(forms.ModelForm):
2217 def clean_name(self):
2218 # do something that validates your data
2219 return self.cleaned_data["name"]
2220
2221 It is important you use a ``ModelForm`` here otherwise things can break. See
2222 the :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
2223 </ref/forms/validation>` and, more specifically, the
2224 :ref:`model form validation notes <overriding-modelform-clean-method>` for more
2225 information.
2226
2227 .. _admin-inlines:
2228
2229 ``InlineModelAdmin`` objects
2230 ============================
2231
2232 .. class:: InlineModelAdmin
2233 .. class:: TabularInline
2234 .. class:: StackedInline
2235
2236 The admin interface has the ability to edit models on the same page as a
2237 parent model. These are called inlines. Suppose you have these two models::
2238
2239 from django.db import models
2240
2241
2242 class Author(models.Model):
2243 name = models.CharField(max_length=100)
2244
2245
2246 class Book(models.Model):
2247 author = models.ForeignKey(Author, on_delete=models.CASCADE)
2248 title = models.CharField(max_length=100)
2249
2250 You can edit the books authored by an author on the author page. You add
2251 inlines to a model by specifying them in a ``ModelAdmin.inlines``::
2252
2253 from django.contrib import admin
2254 from myapp.models import Author, Book
2255
2256
2257 class BookInline(admin.TabularInline):
2258 model = Book
2259
2260
2261 class AuthorAdmin(admin.ModelAdmin):
2262 inlines = [
2263 BookInline,
2264 ]
2265
2266
2267 admin.site.register(Author, AuthorAdmin)
2268
2269 Django provides two subclasses of ``InlineModelAdmin`` and they are:
2270
2271 * :class:`~django.contrib.admin.TabularInline`
2272 * :class:`~django.contrib.admin.StackedInline`
2273
2274 The difference between these two is merely the template used to render
2275 them.
2276
2277 ``InlineModelAdmin`` options
2278 -----------------------------
2279
2280 ``InlineModelAdmin`` shares many of the same features as ``ModelAdmin``, and
2281 adds some of its own (the shared features are actually defined in the
2282 ``BaseModelAdmin`` superclass). The shared features are:
2283
2284 - :attr:`~InlineModelAdmin.form`
2285 - :attr:`~ModelAdmin.fieldsets`
2286 - :attr:`~ModelAdmin.fields`
2287 - :attr:`~ModelAdmin.formfield_overrides`
2288 - :attr:`~ModelAdmin.exclude`
2289 - :attr:`~ModelAdmin.filter_horizontal`
2290 - :attr:`~ModelAdmin.filter_vertical`
2291 - :attr:`~ModelAdmin.ordering`
2292 - :attr:`~ModelAdmin.prepopulated_fields`
2293 - :meth:`~ModelAdmin.get_fieldsets`
2294 - :meth:`~ModelAdmin.get_queryset`
2295 - :attr:`~ModelAdmin.radio_fields`
2296 - :attr:`~ModelAdmin.readonly_fields`
2297 - :attr:`~InlineModelAdmin.raw_id_fields`
2298 - :meth:`~ModelAdmin.formfield_for_choice_field`
2299 - :meth:`~ModelAdmin.formfield_for_foreignkey`
2300 - :meth:`~ModelAdmin.formfield_for_manytomany`
2301 - :meth:`~ModelAdmin.has_module_permission`
2302
2303 The ``InlineModelAdmin`` class adds or customizes:
2304
2305 .. attribute:: InlineModelAdmin.model
2306
2307 The model which the inline is using. This is required.
2308
2309 .. attribute:: InlineModelAdmin.fk_name
2310
2311 The name of the foreign key on the model. In most cases this will be dealt
2312 with automatically, but ``fk_name`` must be specified explicitly if there
2313 are more than one foreign key to the same parent model.
2314
2315 .. attribute:: InlineModelAdmin.formset
2316
2317 This defaults to :class:`~django.forms.models.BaseInlineFormSet`. Using
2318 your own formset can give you many possibilities of customization. Inlines
2319 are built around :ref:`model formsets <model-formsets>`.
2320
2321 .. attribute:: InlineModelAdmin.form
2322
2323 The value for ``form`` defaults to ``ModelForm``. This is what is passed
2324 through to :func:`~django.forms.models.inlineformset_factory` when
2325 creating the formset for this inline.
2326
2327 .. warning::
2328 When writing custom validation for ``InlineModelAdmin`` forms, be cautious
2329 of writing validation that relies on features of the parent model. If the
2330 parent model fails to validate, it may be left in an inconsistent state as
2331 described in the warning in :ref:`validation-on-modelform`.
2332
2333 .. attribute:: InlineModelAdmin.classes
2334
2335 A list or tuple containing extra CSS classes to apply to the fieldset that
2336 is rendered for the inlines. Defaults to ``None``. As with classes
2337 configured in :attr:`~ModelAdmin.fieldsets`, inlines with a ``collapse``
2338 class will be initially collapsed using an expandable widget.
2339
2340 .. versionchanged:: 5.1
2341
2342 ``fieldsets`` using the ``collapse`` class now use ``<details>`` and
2343 ``<summary>`` elements, provided they define a ``name``.
2344
2345 .. attribute:: InlineModelAdmin.extra
2346
2347 This controls the number of extra forms the formset will display in
2348 addition to the initial forms. Defaults to 3. See the
2349 :doc:`formsets documentation </topics/forms/formsets>` for more
2350 information.
2351
2352 For users with JavaScript-enabled browsers, an "Add another" link is
2353 provided to enable any number of additional inlines to be added in addition
2354 to those provided as a result of the ``extra`` argument.
2355
2356 The dynamic link will not appear if the number of currently displayed forms
2357 exceeds ``max_num``, or if the user does not have JavaScript enabled.
2358
2359 :meth:`InlineModelAdmin.get_extra` also allows you to customize the number
2360 of extra forms.
2361
2362 .. attribute:: InlineModelAdmin.max_num
2363
2364 This controls the maximum number of forms to show in the inline. This
2365 doesn't directly correlate to the number of objects, but can if the value
2366 is small enough. See :ref:`model-formsets-max-num` for more information.
2367
2368 :meth:`InlineModelAdmin.get_max_num` also allows you to customize the
2369 maximum number of extra forms.
2370
2371 .. attribute:: InlineModelAdmin.min_num
2372
2373 This controls the minimum number of forms to show in the inline.
2374 See :func:`~django.forms.models.modelformset_factory` for more information.
2375
2376 :meth:`InlineModelAdmin.get_min_num` also allows you to customize the
2377 minimum number of displayed forms.
2378
2379 .. attribute:: InlineModelAdmin.raw_id_fields
2380
2381 By default, Django's admin uses a select-box interface (<select>) for
2382 fields that are ``ForeignKey``. Sometimes you don't want to incur the
2383 overhead of having to select all the related instances to display in the
2384 drop-down.
2385
2386 ``raw_id_fields`` is a list of fields you would like to change into an
2387 ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
2388
2389 class BookInline(admin.TabularInline):
2390 model = Book
2391 raw_id_fields = ["pages"]
2392
2393
2394 .. attribute:: InlineModelAdmin.template
2395
2396 The template used to render the inline on the page.
2397
2398 .. attribute:: InlineModelAdmin.verbose_name
2399
2400 An override to the :attr:`~django.db.models.Options.verbose_name` from the
2401 model's inner ``Meta`` class.
2402
2403 .. attribute:: InlineModelAdmin.verbose_name_plural
2404
2405 An override to the :attr:`~django.db.models.Options.verbose_name_plural`
2406 from the model's inner ``Meta`` class. If this isn't given and the
2407 :attr:`.InlineModelAdmin.verbose_name` is defined, Django will use
2408 :attr:`.InlineModelAdmin.verbose_name` + ``'s'``.
2409
2410 .. attribute:: InlineModelAdmin.can_delete
2411
2412 Specifies whether or not inline objects can be deleted in the inline.
2413 Defaults to ``True``.
2414
2415 .. attribute:: InlineModelAdmin.show_change_link
2416
2417 Specifies whether or not inline objects that can be changed in the
2418 admin have a link to the change form. Defaults to ``False``.
2419
2420 .. method:: InlineModelAdmin.get_formset(request, obj=None, **kwargs)
2421
2422 Returns a :class:`~django.forms.models.BaseInlineFormSet` class for use in
2423 admin add/change views. ``obj`` is the parent object being edited or
2424 ``None`` when adding a new parent. See the example for
2425 :class:`ModelAdmin.get_formsets_with_inlines`.
2426
2427 .. method:: InlineModelAdmin.get_extra(request, obj=None, **kwargs)
2428
2429 Returns the number of extra inline forms to use. By default, returns the
2430 :attr:`InlineModelAdmin.extra` attribute.
2431
2432 Override this method to programmatically determine the number of extra
2433 inline forms. For example, this may be based on the model instance
2434 (passed as the keyword argument ``obj``)::
2435
2436 class BinaryTreeAdmin(admin.TabularInline):
2437 model = BinaryTree
2438
2439 def get_extra(self, request, obj=None, **kwargs):
2440 extra = 2
2441 if obj:
2442 return extra - obj.binarytree_set.count()
2443 return extra
2444
2445 .. method:: InlineModelAdmin.get_max_num(request, obj=None, **kwargs)
2446
2447 Returns the maximum number of extra inline forms to use. By default,
2448 returns the :attr:`InlineModelAdmin.max_num` attribute.
2449
2450 Override this method to programmatically determine the maximum number of
2451 inline forms. For example, this may be based on the model instance
2452 (passed as the keyword argument ``obj``)::
2453
2454 class BinaryTreeAdmin(admin.TabularInline):
2455 model = BinaryTree
2456
2457 def get_max_num(self, request, obj=None, **kwargs):
2458 max_num = 10
2459 if obj and obj.parent:
2460 return max_num - 5
2461 return max_num
2462
2463 .. method:: InlineModelAdmin.get_min_num(request, obj=None, **kwargs)
2464
2465 Returns the minimum number of inline forms to use. By default,
2466 returns the :attr:`InlineModelAdmin.min_num` attribute.
2467
2468 Override this method to programmatically determine the minimum number of
2469 inline forms. For example, this may be based on the model instance
2470 (passed as the keyword argument ``obj``).
2471
2472 .. method:: InlineModelAdmin.has_add_permission(request, obj)
2473
2474 Should return ``True`` if adding an inline object is permitted, ``False``
2475 otherwise. ``obj`` is the parent object being edited or ``None`` when
2476 adding a new parent.
2477
2478 .. method:: InlineModelAdmin.has_change_permission(request, obj=None)
2479
2480 Should return ``True`` if editing an inline object is permitted, ``False``
2481 otherwise. ``obj`` is the parent object being edited.
2482
2483 .. method:: InlineModelAdmin.has_delete_permission(request, obj=None)
2484
2485 Should return ``True`` if deleting an inline object is permitted, ``False``
2486 otherwise. ``obj`` is the parent object being edited.
2487
2488 .. note::
2489 The ``obj`` argument passed to ``InlineModelAdmin`` methods is the parent
2490 object being edited or ``None`` when adding a new parent.
2491
2492 Working with a model with two or more foreign keys to the same parent model
2493 ---------------------------------------------------------------------------
2494
2495 It is sometimes possible to have more than one foreign key to the same model.
2496 Take this model for instance::
2497
2498 from django.db import models
2499
2500
2501 class Person(models.Model):
2502 name = models.CharField(max_length=128)
2503
2504
2505 class Friendship(models.Model):
2506 to_person = models.ForeignKey(
2507 Person, on_delete=models.CASCADE, related_name="friends"
2508 )
2509 from_person = models.ForeignKey(
2510 Person, on_delete=models.CASCADE, related_name="from_friends"
2511 )
2512
2513 If you wanted to display an inline on the ``Person`` admin add/change pages
2514 you need to explicitly define the foreign key since it is unable to do so
2515 automatically::
2516
2517 from django.contrib import admin
2518 from myapp.models import Friendship, Person
2519
2520
2521 class FriendshipInline(admin.TabularInline):
2522 model = Friendship
2523 fk_name = "to_person"
2524
2525
2526 class PersonAdmin(admin.ModelAdmin):
2527 inlines = [
2528 FriendshipInline,
2529 ]
2530
2531
2532 admin.site.register(Person, PersonAdmin)
2533
2534 Working with many-to-many models
2535 --------------------------------
2536
2537 By default, admin widgets for many-to-many relations will be displayed
2538 on whichever model contains the actual reference to the
2539 :class:`~django.db.models.ManyToManyField`. Depending on your ``ModelAdmin``
2540 definition, each many-to-many field in your model will be represented by a
2541 standard HTML ``<select multiple>``, a horizontal or vertical filter, or a
2542 ``raw_id_fields`` widget. However, it is also possible to replace these
2543 widgets with inlines.
2544
2545 Suppose we have the following models::
2546
2547 from django.db import models
2548
2549
2550 class Person(models.Model):
2551 name = models.CharField(max_length=128)
2552
2553
2554 class Group(models.Model):
2555 name = models.CharField(max_length=128)
2556 members = models.ManyToManyField(Person, related_name="groups")
2557
2558 If you want to display many-to-many relations using an inline, you can do
2559 so by defining an ``InlineModelAdmin`` object for the relationship::
2560
2561 from django.contrib import admin
2562 from myapp.models import Group
2563
2564
2565 class MembershipInline(admin.TabularInline):
2566 model = Group.members.through
2567
2568
2569 class GroupAdmin(admin.ModelAdmin):
2570 inlines = [
2571 MembershipInline,
2572 ]
2573 exclude = ["members"]
2574
2575
2576 admin.site.register(Group, GroupAdmin)
2577
2578 There are two features worth noting in this example.
2579
2580 Firstly - the ``MembershipInline`` class references ``Group.members.through``.
2581 The ``through`` attribute is a reference to the model that manages the
2582 many-to-many relation. This model is automatically created by Django when you
2583 define a many-to-many field.
2584
2585 Secondly, the ``GroupAdmin`` must manually exclude the ``members`` field.
2586 Django displays an admin widget for a many-to-many field on the model that
2587 defines the relation (in this case, ``Group``). If you want to use an inline
2588 model to represent the many-to-many relationship, you must tell Django's admin
2589 to *not* display this widget - otherwise you will end up with two widgets on
2590 your admin page for managing the relation.
2591
2592 Note that when using this technique the
2593 :data:`~django.db.models.signals.m2m_changed` signals aren't triggered. This
2594 is because as far as the admin is concerned, ``through`` is just a model with
2595 two foreign key fields rather than a many-to-many relation.
2596
2597 In all other respects, the ``InlineModelAdmin`` is exactly the same as any
2598 other. You can customize the appearance using any of the normal
2599 ``ModelAdmin`` properties.
2600
2601 Working with many-to-many intermediary models
2602 ---------------------------------------------
2603
2604 When you specify an intermediary model using the ``through`` argument to a
2605 :class:`~django.db.models.ManyToManyField`, the admin will not display a
2606 widget by default. This is because each instance of that intermediary model
2607 requires more information than could be displayed in a single widget, and the
2608 layout required for multiple widgets will vary depending on the intermediate
2609 model.
2610
2611 However, we still want to be able to edit that information inline. Fortunately,
2612 we can do this with inline admin models. Suppose we have the following models::
2613
2614 from django.db import models
2615
2616
2617 class Person(models.Model):
2618 name = models.CharField(max_length=128)
2619
2620
2621 class Group(models.Model):
2622 name = models.CharField(max_length=128)
2623 members = models.ManyToManyField(Person, through="Membership")
2624
2625
2626 class Membership(models.Model):
2627 person = models.ForeignKey(Person, on_delete=models.CASCADE)
2628 group = models.ForeignKey(Group, on_delete=models.CASCADE)
2629 date_joined = models.DateField()
2630 invite_reason = models.CharField(max_length=64)
2631
2632 class Meta:
2633 constraints = [
2634 models.UniqueConstraint(
2635 fields=["person", "group"], name="unique_person_group"
2636 )
2637 ]
2638
2639 The first step in displaying this intermediate model in the admin is to
2640 define an inline class for the ``Membership`` model::
2641
2642 class MembershipInline(admin.TabularInline):
2643 model = Membership
2644 extra = 1
2645
2646 This example uses the default ``InlineModelAdmin`` values for the
2647 ``Membership`` model, and limits the extra add forms to one. This could be
2648 customized using any of the options available to ``InlineModelAdmin`` classes.
2649
2650 Now create admin views for the ``Person`` and ``Group`` models::
2651
2652 class PersonAdmin(admin.ModelAdmin):
2653 inlines = [MembershipInline]
2654
2655
2656 class GroupAdmin(admin.ModelAdmin):
2657 inlines = [MembershipInline]
2658
2659 Finally, register your ``Person`` and ``Group`` models with the admin site::
2660
2661 admin.site.register(Person, PersonAdmin)
2662 admin.site.register(Group, GroupAdmin)
2663
2664 Now your admin site is set up to edit ``Membership`` objects inline from
2665 either the ``Person`` or the ``Group`` detail pages.
2666
2667 .. _using-generic-relations-as-an-inline:
2668
2669 Using generic relations as an inline
2670 ------------------------------------
2671
2672 It is possible to use an inline with generically related objects. Let's say
2673 you have the following models::
2674
2675 from django.contrib.contenttypes.fields import GenericForeignKey
2676 from django.contrib.contenttypes.models import ContentType
2677 from django.db import models
2678
2679
2680 class Image(models.Model):
2681 image = models.ImageField(upload_to="images")
2682 content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
2683 object_id = models.PositiveIntegerField()
2684 content_object = GenericForeignKey("content_type", "object_id")
2685
2686
2687 class Product(models.Model):
2688 name = models.CharField(max_length=100)
2689
2690 If you want to allow editing and creating an ``Image`` instance on the
2691 ``Product``, add/change views you can use
2692 :class:`~django.contrib.contenttypes.admin.GenericTabularInline`
2693 or :class:`~django.contrib.contenttypes.admin.GenericStackedInline` (both
2694 subclasses of :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)
2695 provided by :mod:`~django.contrib.contenttypes.admin`. They implement tabular
2696 and stacked visual layouts for the forms representing the inline objects,
2697 respectively, just like their non-generic counterparts. They behave just like
2698 any other inline. In your ``admin.py`` for this example app::
2699
2700 from django.contrib import admin
2701 from django.contrib.contenttypes.admin import GenericTabularInline
2702
2703 from myapp.models import Image, Product
2704
2705
2706 class ImageInline(GenericTabularInline):
2707 model = Image
2708
2709
2710 class ProductAdmin(admin.ModelAdmin):
2711 inlines = [
2712 ImageInline,
2713 ]
2714
2715
2716 admin.site.register(Product, ProductAdmin)
2717
2718 See the :doc:`contenttypes documentation </ref/contrib/contenttypes>` for more
2719 specific information.
2720
2721 .. _admin-overriding-templates:
2722
2723 Overriding admin templates
2724 ==========================
2725
2726 You can override many of the templates which the admin module uses to generate
2727 the various pages of an admin site. You can even override a few of these
2728 templates for a specific app, or a specific model.
2729
2730 Set up your projects admin template directories
2731 -----------------------------------------------
2732
2733 The admin template files are located in the
2734 :source:`django/contrib/admin/templates/admin` directory.
2735
2736 In order to override one or more of them, first create an ``admin`` directory
2737 in your project's ``templates`` directory. This can be any of the directories
2738 you specified in the :setting:`DIRS <TEMPLATES-DIRS>` option of the
2739 ``DjangoTemplates`` backend in the :setting:`TEMPLATES` setting. If you have
2740 customized the ``'loaders'`` option, be sure
2741 ``'django.template.loaders.filesystem.Loader'`` appears before
2742 ``'django.template.loaders.app_directories.Loader'`` so that your custom
2743 templates will be found by the template loading system before those that are
2744 included with :mod:`django.contrib.admin`.
2745
2746 Within this ``admin`` directory, create sub-directories named after your app.
2747 Within these app subdirectories create sub-directories named after your models.
2748 Note, that the admin app will lowercase the model name when looking for the
2749 directory, so make sure you name the directory in all lowercase if you are
2750 going to run your app on a case-sensitive filesystem.
2751
2752 To override an admin template for a specific app, copy and edit the template
2753 from the :source:`django/contrib/admin/templates/admin` directory, and save it to one
2754 of the directories you just created.
2755
2756 For example, if we wanted to add a tool to the change list view for all the
2757 models in an app named ``my_app``, we would copy
2758 ``contrib/admin/templates/admin/change_list.html`` to the
2759 ``templates/admin/my_app/`` directory of our project, and make any necessary
2760 changes.
2761
2762 If we wanted to add a tool to the change list view for only a specific model
2763 named 'Page', we would copy that same file to the
2764 ``templates/admin/my_app/page`` directory of our project.
2765
2766 Overriding vs. replacing an admin template
2767 ------------------------------------------
2768
2769 Because of the modular design of the admin templates, it is usually neither
2770 necessary nor advisable to replace an entire template. It is almost always
2771 better to override only the section of the template which you need to change.
2772
2773 To continue the example above, we want to add a new link next to the
2774 ``History`` tool for the ``Page`` model. After looking at ``change_form.html``
2775 we determine that we only need to override the ``object-tools-items`` block.
2776 Therefore here is our new ``change_form.html`` :
2777
2778 .. code-block:: html+django
2779
2780 {% extends "admin/change_form.html" %}
2781 {% load i18n admin_urls %}
2782 {% block object-tools-items %}
2783 <li>
2784 <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% translate "History" %}</a>
2785 </li>
2786 <li>
2787 <a href="mylink/" class="historylink">My Link</a>
2788 </li>
2789 {% if has_absolute_url %}
2790 <li>
2791 <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% translate "View on site" %}</a>
2792 </li>
2793 {% endif %}
2794 {% endblock %}
2795
2796 And that's it! If we placed this file in the ``templates/admin/my_app``
2797 directory, our link would appear on the change form for all models within
2798 my_app.
2799
2800 .. _admin-templates-overridden-per-app-or-model:
2801
2802 Templates which may be overridden per app or model
2803 --------------------------------------------------
2804
2805 Not every template in ``contrib/admin/templates/admin`` may be overridden per
2806 app or per model. The following can:
2807
2808 * ``actions.html``
2809 * ``app_index.html``
2810 * ``change_form.html``
2811 * ``change_form_object_tools.html``
2812 * ``change_list.html``
2813 * ``change_list_object_tools.html``
2814 * ``change_list_results.html``
2815 * ``date_hierarchy.html``
2816 * ``delete_confirmation.html``
2817 * ``object_history.html``
2818 * ``pagination.html``
2819 * ``popup_response.html``
2820 * ``prepopulated_fields_js.html``
2821 * ``search_form.html``
2822 * ``submit_line.html``
2823
2824 For those templates that cannot be overridden in this way, you may still
2825 override them for your entire project by placing the new version in your
2826 ``templates/admin`` directory. This is particularly useful to create custom 404
2827 and 500 pages.
2828
2829 .. note::
2830
2831 Some of the admin templates, such as ``change_list_results.html`` are used
2832 to render custom inclusion tags. These may be overridden, but in such cases
2833 you are probably better off creating your own version of the tag in
2834 question and giving it a different name. That way you can use it
2835 selectively.
2836
2837 Root and login templates
2838 ------------------------
2839
2840 If you wish to change the index, login or logout templates, you are better off
2841 creating your own ``AdminSite`` instance (see below), and changing the
2842 :attr:`AdminSite.index_template` , :attr:`AdminSite.login_template` or
2843 :attr:`AdminSite.logout_template` properties.
2844
2845 .. _admin-theming:
2846
2847 Theming support
2848 ===============
2849
2850 The admin uses CSS variables to define colors and fonts. This allows changing
2851 themes without having to override many individual CSS rules. For example, if
2852 you preferred purple instead of blue you could add a ``admin/base.html``
2853 template override to your project:
2854
2855 .. code-block:: html+django
2856
2857 {% extends 'admin/base.html' %}
2858
2859 {% block extrastyle %}{{ block.super }}
2860 <style>
2861 html[data-theme="light"], :root {
2862 --primary: #9774d5;
2863 --secondary: #785cab;
2864 --link-fg: #7c449b;
2865 --link-selected-fg: #8f5bb2;
2866 }
2867 </style>
2868 {% endblock %}
2869
2870 The list of CSS variables are defined at
2871 :source:`django/contrib/admin/static/admin/css/base.css`.
2872
2873 Dark mode variables, respecting the `prefers-color-scheme`_ media query, are
2874 defined at :source:`django/contrib/admin/static/admin/css/dark_mode.css`. This is
2875 linked to the document in ``{% block dark-mode-vars %}``.
2876
2877 .. _prefers-color-scheme: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
2878
2879 .. _extrabody:
2880
2881 ``extrabody`` block
2882 ===================
2883
2884 .. versionadded:: 5.2
2885
2886 You can add custom HTML, JavaScript, or other content to appear just before the
2887 closing ``</body>`` tag of templates that extend ``admin/base.html`` by
2888 extending the ``extrabody`` block. For example, if you want an alert to appear
2889 on page load you could add a ``admin/base.html`` template override to your
2890 project:
2891
2892 .. code-block:: html+django
2893
2894 {% extends 'admin/base.html' %}
2895
2896 {% block extrabody %}
2897 {{ block.super }}
2898 <script>
2899 document.addEventListener('DOMContentLoaded', function() {
2900 window.alert('Welcome!');
2901 });
2902 </script>
2903 {% endblock extrabody %}
2904
2905 ``AdminSite`` objects
2906 =====================
2907
2908 .. class:: AdminSite(name='admin')
2909
2910 A Django administrative site is represented by an instance of
2911 ``django.contrib.admin.sites.AdminSite``; by default, an instance of
2912 this class is created as ``django.contrib.admin.site`` and you can
2913 register your models and ``ModelAdmin`` instances with it.
2914
2915 If you want to customize the default admin site, you can :ref:`override it
2916 <overriding-default-admin-site>`.
2917
2918 When constructing an instance of an ``AdminSite``, you can provide
2919 a unique instance name using the ``name`` argument to the constructor. This
2920 instance name is used to identify the instance, especially when
2921 :ref:`reversing admin URLs <admin-reverse-urls>`. If no instance name is
2922 provided, a default instance name of ``admin`` will be used.
2923 See :ref:`customizing-adminsite` for an example of customizing the
2924 :class:`AdminSite` class.
2925
2926 .. data:: django.contrib.admin.sites.all_sites
2927
2928 A :class:`~weakref.WeakSet` contains all admin site instances.
2929
2930 ``AdminSite`` attributes
2931 ------------------------
2932
2933 Templates can override or extend base admin templates as described in
2934 :ref:`admin-overriding-templates`.
2935
2936 .. attribute:: AdminSite.site_header
2937
2938 The text to put at the top of each admin page, as a ``<div>`` (a string).
2939 By default, this is "Django administration".
2940
2941 .. attribute:: AdminSite.site_title
2942
2943 The text to put at the end of each admin page's ``<title>`` (a string). By
2944 default, this is "Django site admin".
2945
2946 .. attribute:: AdminSite.site_url
2947
2948 The URL for the "View site" link at the top of each admin page. By default,
2949 ``site_url`` is ``/``. Set it to ``None`` to remove the link.
2950
2951 For sites running on a subpath, the :meth:`each_context` method checks if
2952 the current request has ``request.META['SCRIPT_NAME']`` set and uses that
2953 value if ``site_url`` isn't set to something other than ``/``.
2954
2955 .. attribute:: AdminSite.index_title
2956
2957 The text to put at the top of the admin index page (a string). By default,
2958 this is "Site administration".
2959
2960 .. attribute:: AdminSite.index_template
2961
2962 Path to a custom template that will be used by the admin site main index
2963 view.
2964
2965 .. attribute:: AdminSite.app_index_template
2966
2967 Path to a custom template that will be used by the admin site app index view.
2968
2969 .. attribute:: AdminSite.empty_value_display
2970
2971 The string to use for displaying empty values in the admin site's change
2972 list. Defaults to a dash. The value can also be overridden on a per
2973 ``ModelAdmin`` basis and on a custom field within a ``ModelAdmin`` by
2974 setting an ``empty_value_display`` attribute on the field. See
2975 :attr:`ModelAdmin.empty_value_display` for examples.
2976
2977 .. attribute:: AdminSite.enable_nav_sidebar
2978
2979 A boolean value that determines whether to show the navigation sidebar
2980 on larger screens. By default, it is set to ``True``.
2981
2982 .. attribute:: AdminSite.final_catch_all_view
2983
2984 A boolean value that determines whether to add a final catch-all view to
2985 the admin that redirects unauthenticated users to the login page. By
2986 default, it is set to ``True``.
2987
2988 .. warning::
2989
2990 Setting this to ``False`` is not recommended as the view protects
2991 against a potential model enumeration privacy issue.
2992
2993 .. attribute:: AdminSite.login_template
2994
2995 Path to a custom template that will be used by the admin site login view.
2996
2997 .. attribute:: AdminSite.login_form
2998
2999 Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that
3000 will be used by the admin site login view.
3001
3002 .. attribute:: AdminSite.logout_template
3003
3004 Path to a custom template that will be used by the admin site logout view.
3005
3006 .. attribute:: AdminSite.password_change_template
3007
3008 Path to a custom template that will be used by the admin site password
3009 change view.
3010
3011 .. attribute:: AdminSite.password_change_done_template
3012
3013 Path to a custom template that will be used by the admin site password
3014 change done view.
3015
3016 ``AdminSite`` methods
3017 ---------------------
3018
3019 .. method:: AdminSite.each_context(request)
3020
3021 Returns a dictionary of variables to put in the template context for
3022 every page in the admin site.
3023
3024 Includes the following variables and values by default:
3025
3026 * ``site_header``: :attr:`AdminSite.site_header`
3027 * ``site_title``: :attr:`AdminSite.site_title`
3028 * ``site_url``: :attr:`AdminSite.site_url`
3029 * ``has_permission``: :meth:`AdminSite.has_permission`
3030 * ``available_apps``: a list of applications from the :doc:`application registry
3031 </ref/applications/>` available for the current user. Each entry in the
3032 list is a dict representing an application with the following keys:
3033
3034 * ``app_label``: the application label
3035 * ``app_url``: the URL of the application index in the admin
3036 * ``has_module_perms``: a boolean indicating if displaying and accessing of
3037 the module's index page is permitted for the current user
3038 * ``models``: a list of the models available in the application
3039
3040 Each model is a dict with the following keys:
3041
3042 * ``model``: the model class
3043 * ``object_name``: class name of the model
3044 * ``name``: plural name of the model
3045 * ``perms``: a ``dict`` tracking ``add``, ``change``, ``delete``, and
3046 ``view`` permissions
3047 * ``admin_url``: admin changelist URL for the model
3048 * ``add_url``: admin URL to add a new model instance
3049
3050 * ``is_popup``: whether the current page is displayed in a popup window
3051 * ``is_nav_sidebar_enabled``: :attr:`AdminSite.enable_nav_sidebar`
3052 * ``log_entries``: :meth:`.AdminSite.get_log_entries`
3053
3054 .. method:: AdminSite.get_app_list(request, app_label=None)
3055
3056 Returns a list of applications from the :doc:`application registry
3057 </ref/applications/>` available for the current user. You can optionally
3058 pass an ``app_label`` argument to get details for a single app. Each entry
3059 in the list is a dictionary representing an application with the following
3060 keys:
3061
3062 * ``app_label``: the application label
3063 * ``app_url``: the URL of the application index in the admin
3064 * ``has_module_perms``: a boolean indicating if displaying and accessing of
3065 the module's index page is permitted for the current user
3066 * ``models``: a list of the models available in the application
3067 * ``name``: name of the application
3068
3069 Each model is a dictionary with the following keys:
3070
3071 * ``model``: the model class
3072 * ``object_name``: class name of the model
3073 * ``name``: plural name of the model
3074 * ``perms``: a ``dict`` tracking ``add``, ``change``, ``delete``, and
3075 ``view`` permissions
3076 * ``admin_url``: admin changelist URL for the model
3077 * ``add_url``: admin URL to add a new model instance
3078
3079 Lists of applications and models are sorted alphabetically by their names.
3080 You can override this method to change the default order on the admin index
3081 page.
3082
3083 .. method:: AdminSite.has_permission(request)
3084
3085 Returns ``True`` if the user for the given ``HttpRequest`` has permission
3086 to view at least one page in the admin site. Defaults to requiring both
3087 :attr:`User.is_active <django.contrib.auth.models.User.is_active>` and
3088 :attr:`User.is_staff <django.contrib.auth.models.User.is_staff>` to be
3089 ``True``.
3090
3091 .. method:: AdminSite.register(model_or_iterable, admin_class=None, **options)
3092
3093 Registers the given model class (or iterable of classes) with the given
3094 ``admin_class``. ``admin_class`` defaults to
3095 :class:`~django.contrib.admin.ModelAdmin` (the default admin options). If
3096 keyword arguments are given -- e.g. ``list_display`` -- they'll be applied
3097 as options to the admin class.
3098
3099 Raises :class:`~django.core.exceptions.ImproperlyConfigured` if a model is
3100 abstract. and ``django.contrib.admin.exceptions.AlreadyRegistered`` if a
3101 model is already registered.
3102
3103 .. method:: AdminSite.unregister(model_or_iterable)
3104
3105 Unregisters the given model class (or iterable of classes).
3106
3107 Raises ``django.contrib.admin.exceptions.NotRegistered`` if a model isn't
3108 already registered.
3109
3110 .. method:: AdminSite.get_model_admin(model)
3111
3112 Returns an admin class for the given model class. Raises
3113 ``django.contrib.admin.exceptions.NotRegistered`` if a model isn't registered.
3114
3115 .. method:: AdminSite.get_log_entries(request)
3116
3117 Returns a queryset for the related
3118 :class:`~django.contrib.admin.models.LogEntry` instances, shown on the site
3119 index page. This method can be overridden to filter the log entries by
3120 other criteria.
3121
3122 .. _hooking-adminsite-to-urlconf:
3123
3124 Hooking ``AdminSite`` instances into your URLconf
3125 -------------------------------------------------
3126
3127 The last step in setting up the Django admin is to hook your ``AdminSite``
3128 instance into your URLconf. Do this by pointing a given URL at the
3129 ``AdminSite.urls`` method. It is not necessary to use
3130 :func:`~django.urls.include()`.
3131
3132 In this example, we register the default ``AdminSite`` instance
3133 ``django.contrib.admin.site`` at the URL ``/admin/`` ::
3134
3135 # urls.py
3136 from django.contrib import admin
3137 from django.urls import path
3138
3139 urlpatterns = [
3140 path("admin/", admin.site.urls),
3141 ]
3142
3143 .. _customizing-adminsite:
3144
3145 Customizing the :class:`AdminSite` class
3146 ----------------------------------------
3147
3148 If you'd like to set up your own admin site with custom behavior, you're free
3149 to subclass ``AdminSite`` and override or add anything you like. Then, create
3150 an instance of your ``AdminSite`` subclass (the same way you'd instantiate any
3151 other Python class) and register your models and ``ModelAdmin`` subclasses with
3152 it instead of with the default site. Finally, update :file:`myproject/urls.py`
3153 to reference your :class:`AdminSite` subclass.
3154
3155 .. code-block:: python
3156 :caption: ``myapp/admin.py``
3157
3158 from django.contrib import admin
3159
3160 from .models import MyModel
3161
3162
3163 class MyAdminSite(admin.AdminSite):
3164 site_header = "Monty Python administration"
3165
3166
3167 admin_site = MyAdminSite(name="myadmin")
3168 admin_site.register(MyModel)
3169
3170
3171 .. code-block:: python
3172 :caption: ``myproject/urls.py``
3173
3174 from django.urls import path
3175
3176 from myapp.admin import admin_site
3177
3178 urlpatterns = [
3179 path("myadmin/", admin_site.urls),
3180 ]
3181
3182 Note that you may not want autodiscovery of ``admin`` modules when using your
3183 own ``AdminSite`` instance since you will likely be importing all the per-app
3184 ``admin`` modules in your ``myproject.admin`` module. This means you need to
3185 put ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of
3186 ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting.
3187
3188 .. _overriding-default-admin-site:
3189
3190 Overriding the default admin site
3191 ---------------------------------
3192
3193 You can override the default ``django.contrib.admin.site`` by setting the
3194 :attr:`~.SimpleAdminConfig.default_site` attribute of a custom ``AppConfig``
3195 to the dotted import path of either a ``AdminSite`` subclass or a callable that
3196 returns a site instance.
3197
3198 .. code-block:: python
3199 :caption: ``myproject/admin.py``
3200
3201 from django.contrib import admin
3202
3203
3204 class MyAdminSite(admin.AdminSite): ...
3205
3206 .. code-block:: python
3207 :caption: ``myproject/apps.py``
3208
3209 from django.contrib.admin.apps import AdminConfig
3210
3211
3212 class MyAdminConfig(AdminConfig):
3213 default_site = "myproject.admin.MyAdminSite"
3214
3215 .. code-block:: python
3216 :caption: ``myproject/settings.py``
3217
3218 INSTALLED_APPS = [
3219 # ...
3220 "myproject.apps.MyAdminConfig", # replaces 'django.contrib.admin'
3221 # ...
3222 ]
3223
3224 .. _multiple-admin-sites:
3225
3226 Multiple admin sites in the same URLconf
3227 ----------------------------------------
3228
3229 You can create multiple instances of the admin site on the same Django-powered
3230 website. Create multiple instances of ``AdminSite`` and place each one at a
3231 different URL.
3232
3233 In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
3234 separate versions of the admin site -- using the ``AdminSite`` instances
3235 ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
3236 respectively::
3237
3238 # urls.py
3239 from django.urls import path
3240 from myproject.admin import advanced_site, basic_site
3241
3242 urlpatterns = [
3243 path("basic-admin/", basic_site.urls),
3244 path("advanced-admin/", advanced_site.urls),
3245 ]
3246
3247 ``AdminSite`` instances take a single argument to their constructor, their
3248 name, which can be anything you like. This argument becomes the prefix to the
3249 URL names for the purposes of :ref:`reversing them<admin-reverse-urls>`. This
3250 is only necessary if you are using more than one ``AdminSite``.
3251
3252 Adding views to admin sites
3253 ---------------------------
3254
3255 Just like :class:`ModelAdmin`, :class:`AdminSite` provides a
3256 :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method
3257 that can be overridden to define additional views for the site. To add
3258 a new view to your admin site, extend the base
3259 :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method to include
3260 a pattern for your new view.
3261
3262 .. note::
3263
3264 Any view you render that uses the admin templates, or extends the base
3265 admin template, should set ``request.current_app`` before rendering the
3266 template. It should be set to either ``self.name`` if your view is on an
3267 ``AdminSite`` or ``self.admin_site.name`` if your view is on a
3268 ``ModelAdmin``.
3269
3270 .. _auth_password_reset:
3271
3272 Adding a password reset feature
3273 -------------------------------
3274
3275 You can add a password reset feature to the admin site by adding a few lines to
3276 your URLconf. Specifically, add these four patterns::
3277
3278 from django.contrib import admin
3279 from django.contrib.auth import views as auth_views
3280
3281 path(
3282 "admin/password_reset/",
3283 auth_views.PasswordResetView.as_view(
3284 extra_context={"site_header": admin.site.site_header}
3285 ),
3286 name="admin_password_reset",
3287 ),
3288 path(
3289 "admin/password_reset/done/",
3290 auth_views.PasswordResetDoneView.as_view(
3291 extra_context={"site_header": admin.site.site_header}
3292 ),
3293 name="password_reset_done",
3294 ),
3295 path(
3296 "reset/<uidb64>/<token>/",
3297 auth_views.PasswordResetConfirmView.as_view(
3298 extra_context={"site_header": admin.site.site_header}
3299 ),
3300 name="password_reset_confirm",
3301 ),
3302 path(
3303 "reset/done/",
3304 auth_views.PasswordResetCompleteView.as_view(
3305 extra_context={"site_header": admin.site.site_header}
3306 ),
3307 name="password_reset_complete",
3308 ),
3309
3310 (This assumes you've added the admin at ``admin/`` and requires that you put
3311 the URLs starting with ``^admin/`` before the line that includes the admin app
3312 itself).
3313
3314 The presence of the ``admin_password_reset`` named URL will cause a "forgotten
3315 your password?" link to appear on the default admin log-in page under the
3316 password box.
3317
3318 ``LogEntry`` objects
3319 ====================
3320
3321 .. class:: models.LogEntry
3322
3323 The ``LogEntry`` class tracks additions, changes, and deletions of objects
3324 done through the admin interface.
3325
3326 .. currentmodule:: django.contrib.admin.models
3327
3328 ``LogEntry`` attributes
3329 -----------------------
3330
3331 .. attribute:: LogEntry.action_time
3332
3333 The date and time of the action.
3334
3335 .. attribute:: LogEntry.user
3336
3337 The user (an :setting:`AUTH_USER_MODEL` instance) who performed the
3338 action.
3339
3340 .. attribute:: LogEntry.content_type
3341
3342 The :class:`~django.contrib.contenttypes.models.ContentType` of the
3343 modified object.
3344
3345 .. attribute:: LogEntry.object_id
3346
3347 The textual representation of the modified object's primary key.
3348
3349 .. attribute:: LogEntry.object_repr
3350
3351 The object`s ``repr()`` after the modification.
3352
3353 .. attribute:: LogEntry.action_flag
3354
3355 The type of action logged: ``ADDITION``, ``CHANGE``, ``DELETION``.
3356
3357 For example, to get a list of all additions done through the admin::
3358
3359 from django.contrib.admin.models import ADDITION, LogEntry
3360
3361 LogEntry.objects.filter(action_flag=ADDITION)
3362
3363 .. attribute:: LogEntry.change_message
3364
3365 The detailed description of the modification. In the case of an edit, for
3366 example, the message contains a list of the edited fields. The Django admin
3367 site formats this content as a JSON structure, so that
3368 :meth:`get_change_message` can recompose a message translated in the current
3369 user language. Custom code might set this as a plain string though. You are
3370 advised to use the :meth:`get_change_message` method to retrieve this value
3371 instead of accessing it directly.
3372
3373 ``LogEntry`` methods
3374 --------------------
3375
3376 .. method:: LogEntry.get_edited_object()
3377
3378 A shortcut that returns the referenced object.
3379
3380 .. method:: LogEntry.get_change_message()
3381
3382 Formats and translates :attr:`change_message` into the current user
3383 language. Messages created before Django 1.10 will always be displayed in
3384 the language in which they were logged.
3385
3386 .. currentmodule:: django.contrib.admin
3387
3388 .. _admin-reverse-urls:
3389
3390 Reversing admin URLs
3391 ====================
3392
3393 When an :class:`AdminSite` is deployed, the views provided by that site are
3394 accessible using Django's :ref:`URL reversing system <naming-url-patterns>`.
3395
3396 The :class:`AdminSite` provides the following named URL patterns:
3397
3398 ========================= ======================== ==================================
3399 Page URL name Parameters
3400 ========================= ======================== ==================================
3401 Index ``index``
3402 Login ``login``
3403 Logout ``logout``
3404 Password change ``password_change``
3405 Password change done ``password_change_done``
3406 i18n JavaScript ``jsi18n``
3407 Application index page ``app_list`` ``app_label``
3408 Redirect to object's page ``view_on_site`` ``content_type_id``, ``object_id``
3409 ========================= ======================== ==================================
3410
3411 Each :class:`ModelAdmin` instance provides an additional set of named URLs:
3412
3413 ====================== =============================================== =============
3414 Page URL name Parameters
3415 ====================== =============================================== =============
3416 Changelist ``{{ app_label }}_{{ model_name }}_changelist``
3417 Add ``{{ app_label }}_{{ model_name }}_add``
3418 History ``{{ app_label }}_{{ model_name }}_history`` ``object_id``
3419 Delete ``{{ app_label }}_{{ model_name }}_delete`` ``object_id``
3420 Change ``{{ app_label }}_{{ model_name }}_change`` ``object_id``
3421 ====================== =============================================== =============
3422
3423 The ``UserAdmin`` provides a named URL:
3424
3425 ====================== =============================================== =============
3426 Page URL name Parameters
3427 ====================== =============================================== =============
3428 Password change ``auth_user_password_change`` ``user_id``
3429 ====================== =============================================== =============
3430
3431 These named URLs are registered with the application namespace ``admin``, and
3432 with an instance namespace corresponding to the name of the Site instance.
3433
3434 So - if you wanted to get a reference to the Change view for a particular
3435 ``Choice`` object (from the polls application) in the default admin, you would
3436 call:
3437
3438 .. code-block:: pycon
3439
3440 >>> from django.urls import reverse
3441 >>> c = Choice.objects.get(...)
3442 >>> change_url = reverse("admin:polls_choice_change", args=(c.id,))
3443
3444 This will find the first registered instance of the admin application
3445 (whatever the instance name), and resolve to the view for changing
3446 ``poll.Choice`` instances in that instance.
3447
3448 If you want to find a URL in a specific admin instance, provide the name of
3449 that instance as a ``current_app`` hint to the reverse call. For example,
3450 if you specifically wanted the admin view from the admin instance named
3451 ``custom``, you would need to call:
3452
3453 .. code-block:: pycon
3454
3455 >>> change_url = reverse("admin:polls_choice_change", args=(c.id,), current_app="custom")
3456
3457 For more details, see the documentation on :ref:`reversing namespaced URLs
3458 <topics-http-reversing-url-namespaces>`.
3459
3460 To allow easier reversing of the admin urls in templates, Django provides an
3461 ``admin_urlname`` filter which takes an action as argument:
3462
3463 .. code-block:: html+django
3464
3465 {% load admin_urls %}
3466 <a href="{% url opts|admin_urlname:'add' %}">Add user</a>
3467 <a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>
3468
3469 The action in the examples above match the last part of the URL names for
3470 :class:`ModelAdmin` instances described above. The ``opts`` variable can be any
3471 object which has an ``app_label`` and ``model_name`` attributes and is usually
3472 supplied by the admin views for the current model.
3473
3474 The ``display`` decorator
3475 =========================
3476
3477 .. function:: display(*, boolean=None, ordering=None, description=None, empty_value=None)
3478
3479 This decorator can be used for setting specific attributes on custom
3480 display functions that can be used with
3481 :attr:`~django.contrib.admin.ModelAdmin.list_display` or
3482 :attr:`~django.contrib.admin.ModelAdmin.readonly_fields`::
3483
3484 @admin.display(
3485 boolean=True,
3486 ordering="-publish_date",
3487 description="Is Published?",
3488 )
3489 def is_published(self, obj):
3490 return obj.publish_date is not None
3491
3492 This is equivalent to setting some attributes (with the original, longer
3493 names) on the function directly::
3494
3495 def is_published(self, obj):
3496 return obj.publish_date is not None
3497
3498
3499 is_published.boolean = True
3500 is_published.admin_order_field = "-publish_date"
3501 is_published.short_description = "Is Published?"
3502
3503 Also note that the ``empty_value`` decorator parameter maps to the
3504 ``empty_value_display`` attribute assigned directly to the function. It
3505 cannot be used in conjunction with ``boolean`` -- they are mutually
3506 exclusive.
3507
3508 Use of this decorator is not compulsory to make a display function, but it
3509 can be useful to use it without arguments as a marker in your source to
3510 identify the purpose of the function::
3511
3512 @admin.display
3513 def published_year(self, obj):
3514 return obj.publish_date.year
3515
3516 In this case it will add no attributes to the function.
3517
3518 .. currentmodule:: django.contrib.admin.views.decorators
3519
3520 The ``staff_member_required`` decorator
3521 =======================================
3522
3523 .. function:: staff_member_required(redirect_field_name='next', login_url='admin:login')
3524
3525 This decorator is used on the admin views that require authorization. A
3526 view decorated with this function will have the following behavior:
3527
3528 * If the user is logged in, is a staff member (``User.is_staff=True``), and
3529 is active (``User.is_active=True``), execute the view normally.
3530
3531 * Otherwise, the request will be redirected to the URL specified by the
3532 ``login_url`` parameter, with the originally requested path in a query
3533 string variable specified by ``redirect_field_name``. For example:
3534 ``/admin/login/?next=/admin/polls/question/3/``.
3535
3536 Example usage::
3537
3538 from django.contrib.admin.views.decorators import staff_member_required
3539
3540
3541 @staff_member_required
3542 def my_view(request): ...