Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 77 ยท The Admin

The Django Admin

Get a working admin site from your models: create a superuser, register models, then tune the list with ModelAdmin, list_display, search_fields and list_filter.

Every site that stores data needs a back office: a place where staff can look up a record, fix a typo, add a product or delete spam. Writing that interface by hand for each model is dull work, and it is exactly the kind of work Django automates. The admin is a complete, secure, ready-made management site that Django builds by reading your models. You register a model, and you immediately get list pages, search, filters, add and edit forms with validation, a delete confirmation, and a history of who changed what.

The admin is meant for trusted staff, not for your public users. This lesson shows how to turn it on, create a superuser, register models, and use ModelAdmin to make the list pages useful with list_display, search_fields and list_filter. The next lesson, Customizing the Admin, goes deeper.

How the admin fits in

flowchart LR
    M["Your models"] -->|"admin.site.register(...)"| A["AdminSite"]
    A --> U["URLs under /admin/"]
    U --> P["List, add, change,<br/>delete and history pages"]
    P -->|"reads and writes"| DB[("Database")]
    S["Staff user<br/>(is_staff, permissions)"] -->|"logs in"| U

Registering a model with the admin site generates a set of URLs and pages for it. Only users flagged as staff, with the right permissions, may use them.

In a normal project the admin is almost free:

  1. django.contrib.admin (and the apps it depends on: auth, contenttypes, sessions, messages) is listed in INSTALLED_APPS. A project created with startproject already has this.
  2. The project's urls.py contains path("admin/", admin.site.urls).
  3. You run python manage.py migrate so the tables for users and permissions exist.
  4. You create a superuser: python manage.py createsuperuser. The command asks for a username, an e-mail address and a password, and creates a user with is_staff=True and is_superuser=True. (Read-only here: you type this in a terminal on your own machine.)
  5. In your app's admin.py you register your models. Django finds that file automatically.
  6. You start the development server and visit /admin/.

The examples below perform the same steps in code. A tiny stand-in package called shop plays the part of your app, and an in-memory SQLite database replaces the file. Instead of typing a password at a prompt, create_superuser is called directly and the test client uses force_login, so no password hashing is needed.

Register a model

The simplest registration is one line: admin.site.register(Book). The admin then offers a changelist (a table of rows), an "add" form and a "change" form for every Book.

Python A first admin site

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 output tells the whole story:

  • Registering the model created four URL names (admin:shop_book_changelist, _add, _change, _delete) under /admin/. You never wrote those routes.
  • A visitor who is not logged in gets a 302 redirect to the admin login page. The admin never shows data to anonymous users.
  • The index page lists Books, plus the Users and Groups that the auth app registers itself.
  • The "add" form was built from the model: one input per field. CharField(max_length=100) has a length limit, DecimalField demands a number, and BooleanField is a checkbox. These are exactly the ModelForm rules, because the admin uses ModelForms internally.
  • Invalid input is rejected with the usual messages; a valid submission redirects back to the list (302).
  • Every change is written to a history log (LogEntry), so you can see who added or changed what.

On the list page, rows show the result of __str__(), which is why a good __str__ matters (see Models and Fields). A model without it displays as "Book object (1)" in the admin.

On a real machine you would type python manage.py createsuperuser, run python manage.py runserver and open http://127.0.0.1:8000/admin/ in the browser to see the pages the code above fetched with the test client. The browser shows a styled interface (the CSS and JavaScript come from static files); the test client shows you the HTML underneath.

ModelAdmin: tune the changelist

admin.site.register(Book) uses default settings. To change how a model behaves in the admin, create a ModelAdmin class and pass it to register. You can write it in the usual way or with the @admin.register(Book) decorator:

Python
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ["title", "author", "price", "in_stock"]
    list_filter = ["in_stock"]
    search_fields = ["title", "author"]
    ordering = ["title"]

The options that matter most for the list page:

Option Effect
list_display Columns shown. Items can be fields, model methods or admin methods. Clicking a header sorts by it.
list_display_links Which columns link to the edit page (the first one by default).
list_filter Sidebar filters, one per listed field (booleans, choices, dates, foreign keys).
search_fields Fields searched by the search box (case-insensitive contains by default). Prefix with ^ for "starts with", = for exact, @ for full-text.
ordering Default sort order for the list.
list_per_page Rows per page (100 by default).
list_editable Columns that can be edited directly in the list.
date_hierarchy Date drill-down navigation above the list.

Search can follow relations too: search_fields = ["title", "author__name"] searches a related model's field.

Python list_display, search_fields and list_filter

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.

Each line corresponds to one option:

  • list_display produced four columns instead of one. The first column becomes the link to the edit page; the boolean in_stock is drawn as an icon in the browser.
  • list_per_page = 2 splits three books over two pages; ?p=2 selects the page, and the counter at the bottom always reports the total.
  • search_fields turned ?q=austen into a database query that checks both title and author. Searching for frank finds Dune through the author field. Several words are combined with AND, each word matching any of the fields.
  • list_filter created the sidebar links "Yes" and "No", which are really URL parameters (?in_stock__exact=0). Filters and search combine in the same query string.
  • A user who is not staff is redirected to the login page, and a staff user who has not been granted permissions for the model gets 403 Forbidden. Superusers pass every permission check; ordinary staff users are given permissions per model (view, add, change, delete) or through groups, as described in Permissions.

The admin is powerful, which is why it deserves care. Do not expose it at the default /admin/ path if you can avoid it, use strong passwords or two-factor authentication, serve it over HTTPS only, and give most staff members only the permissions they need instead of the superuser flag.

Admin tips for beginners

  • Define a meaningful __str__ on every model; it is the label in lists, dropdowns and the history.
  • Register models in the app's admin.py, not in models.py.
  • search_fields on large tables can be slow because contains cannot use ordinary indexes. Prefer ^field ("starts with") where it fits.
  • The admin's forms are ModelForms, so the validation you add to a model (validators, unique=True, clean()) applies in the admin automatically.
  • Deleting from the admin respects on_delete rules and shows what else will be removed first.
  • Anything the admin can do you can also do in code with the ORM; the admin is an interface, not a different database layer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does admin.site.register(Book) give you?

    Registering a model generates the changelist, add, change, delete and history pages automatically. You write no views or templates for them.
  2. 2. Which user can log in to the admin site?

    The admin requires is_staff. Superusers can do everything; other staff users need explicit permissions for each model.
  3. 3. Which option adds a search box and which one adds a sidebar of clickable filters?

    search_fields enables the search box for the listed fields, and list_filter adds the filter links in the sidebar. The other pairing has the roles reversed.
  4. 4. Your model has no __str__ method. How do its rows appear in the admin list?

    Without str Django falls back to the default text such as Book object (1). Define str or use list_display to show meaningful columns.
  5. 5. A staff user who is not a superuser opens a model page and gets 403 Forbidden. What is the likely cause?

    Staff status only opens the door to the admin. Each model needs its own permission, assigned to the user or to one of their groups.

Summary

  • The admin is a ready-made management site generated from your models, intended for trusted staff.
  • It needs django.contrib.admin and its dependencies in INSTALLED_APPS, path("admin/", admin.site.urls) in the URLs, a migrated database and a superuser (createsuperuser).
  • admin.site.register(Model) creates the list, add, change, delete and history pages; every change is logged.
  • The admin forms are ModelForms, so model validation applies automatically.
  • A ModelAdmin customizes the list page: list_display (columns), search_fields (search box), list_filter (sidebar), ordering, list_per_page.
  • Access needs is_staff plus per-model permissions; only superusers bypass them.

Continue with Customizing the Admin to learn about fieldsets, inlines, actions and read-only fields.