Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 77 ยท The Admin

Customizing the Admin

Shape the Django admin to your data: fieldsets, inlines, readonly fields, custom columns with @admin.display, bulk actions, permissions and template overrides.

The admin you get from admin.site.register(Model) is already useful, but a real back office needs more. Editors want related rows on the same page, calculated columns in the list, a button that publishes ten items at once, and fields that are visible but locked. All of that is configuration on the ModelAdmin class, and almost none of it needs custom HTML.

This lesson builds on The Django Admin. You will group fields with fieldsets, edit child rows with inlines, show computed values with @admin.display, write bulk actions, lock things down with permissions, and see where template overrides fit. Every example runs the real admin site in your browser and drives it with the test client.

The admin needs a small amount of setup: the admin, auth, contenttypes, sessions and messages apps, the matching middleware and a template configuration with context processors. The examples below include that setup so they run on their own. In a real project startproject generates it for you.

How the admin pages fit together

Each registered model gets a changelist (the table of rows) and a change form (one row, plus its inlines). The ModelAdmin attributes you set control both.

flowchart TD
    MA["ModelAdmin"] --> CL["Changelist"]
    MA --> CF["Change form"]
    CL --> LD["list_display<br/>list_filter<br/>search_fields<br/>actions"]
    CF --> FS["fieldsets<br/>readonly_fields"]
    CF --> IN["inlines<br/>(child rows)"]
    MA --> PM["has_add_permission<br/>has_change_permission<br/>has_delete_permission"]

Changelist options shape the table, change-form options shape the editing page, and the permission methods decide who may do what.

Fieldsets and read-only fields

By default the change form lists every editable field in model order. fieldsets lets you split them into titled groups. Each group is a pair of a title (or None for no heading) and a dictionary of options. A group can carry CSS classes such as collapse, which folds it away until clicked.

readonly_fields shows a value as plain text instead of an input. It accepts model fields (a creation timestamp, for example), methods on the ModelAdmin, and methods on the model. Read-only fields must also be listed inside fieldsets or fields if you use those options.

Computed values use a method decorated with @admin.display. It sets the column header (description), whether the value renders as a yes/no icon (boolean=True), and which database field the column sorts by (ordering).

Python Fieldsets, read-only fields and computed columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first block of output is get_fieldsets(), the same list the admin renders. The created field has no input on the page because it is read-only: you can see the value but not change it. The author page includes book_set-TOTAL_FORMS, the hidden counter of the inline formset, which leads to the next feature.

Inlines: edit children on the parent page

An inline shows rows of a related model inside the parent's change form. TabularInline renders compact rows; StackedInline stacks every field vertically, which suits wide models. Set model to the child, and optionally extra (empty forms to show), min_num, max_num, fields and readonly_fields. The foreign key is detected automatically when there is exactly one from the child to the parent.

Under the hood an inline is a formset, so saving the parent also validates and saves the children in one request. Inlines cannot nest: an inline cannot have inlines of its own, so deep structures need a different design (or a link to the child's own admin page).

Bulk actions

Select rows on the changelist, pick an action from the dropdown and press Go. An action is a function (or method) that receives the ModelAdmin, the request and a queryset of the selected rows. Decorate it with @admin.action(description=...) to set the dropdown label, and use self.message_user(...) to confirm what happened.

Prefer queryset.update(...) for simple changes. It issues one SQL UPDATE, but it skips save() and signals. Loop and call save() when your model logic depends on them.

Permissions inside the admin

The admin never lets a user do more than their permissions allow. A staff user (is_staff=True) can log in, but each model also needs add, change, delete or view permission, which you grant through users and groups (more in Permissions, Groups and Authorization). On top of that you can override four methods on a ModelAdmin for custom rules:

  • has_module_permission(request) controls whether the app appears on the admin index.
  • has_view_permission(request, obj=None), has_add_permission(request), has_change_permission(request, obj=None) and has_delete_permission(request, obj=None) control each operation. The obj argument is None for list-level checks, so handle both cases.

Overriding get_queryset(request) limits which rows a user sees at all. A common pattern is letting editors see only their own rows, while superusers see everything.

Python Actions and permissions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The action changed two rows with one query and reported it through the messages framework. The reader account can open the list and the read-only form but cannot add, and the form has no save button. The account with no permissions gets a 403 even though it is staff: is_staff only opens the front door.

Overriding admin templates

Everything the admin draws comes from templates inside django.contrib.admin, and you can replace any of them. Django looks in your project's template directories first, so a file at templates/admin/base_site.html wins over the built-in one. To override per model, use templates/admin/<app_label>/<model_name>/change_form.html. Extend the original and fill only the blocks you need:

HTML
{% extends "admin/base_site.html" %}

{% block branding %}
  <h1 id="site-name">Acme back office</h1>
{% endblock %}

Two shortcuts avoid template work. Set admin.site.site_header, site_title and index_title to rename the site, and add class Media: css = {"all": ["admin/extra.css"]} to a ModelAdmin to load your own stylesheet. Template overrides need real template files, so they are not shown as a live example here. See Template Inheritance and Includes for how extends and block work.

Keep the admin for trusted staff. The more you bend it into a public-facing product, the more you fight it. When you need a custom workflow for customers, build normal views and forms instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a staff user (is_staff=True) with no model permissions see in the admin?

    is_staff only allows logging in to the admin site. Each model still needs add, change, delete or view permission, granted to the user or one of their groups.
  2. 2. Which decorator sets the column header of a computed value shown in list_display?

    @admin.display configures a method used as a column or read-only field: its header (description), boolean icon rendering and sort field (ordering). @admin.action is for bulk actions.
  3. 3. Why use queryset.update() in a bulk action, and what is its drawback?

    update() translates to a single SQL statement, which is fast, but it does not call each model's save() method or send pre_save and post_save signals.
  4. 4. Where must a field appear if it is listed in readonly_fields and you also define fieldsets?

    When fieldsets or fields is set, the form shows only what you list. A read-only field must be named there to appear on the page.

Summary

  • fieldsets group and title the fields of the change form; the collapse class folds a group away.
  • readonly_fields displays model fields, admin methods and model methods as plain text.
  • @admin.display names, sorts and formats computed columns; @admin.action names bulk actions.
  • Inlines (TabularInline, StackedInline) edit child rows on the parent page through a formset and cannot be nested.
  • Actions receive a queryset; update() is fast but skips save() and signals.
  • Permissions decide what staff users can do; override the has_*_permission methods and get_queryset for custom rules.
  • Override admin templates by placing a file with the same path in your own templates/admin/ folder.

Next up: Users and Authentication.