Registering & Customizing Models

Register models and control how they appear with ModelAdmin.

Syntax@admin.register(Model)

To manage a model in the admin, register it in your app's admin.py. For more control, define a ModelAdmin class to set options like list_display, list_filter and search_fields.

  • list_display — columns shown in the list.
  • list_filter — sidebar filters.
  • search_fields — a search box.
  • prepopulated_fields — auto-fill slugs from other fields.

Example

Example · python
# blog/admin.py
from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ("title", "author", "published", "created")
    list_filter = ("published", "created")
    search_fields = ("title", "body")
    prepopulated_fields = {"slug": ("title",)}

When to use it

  • A developer registers the Post model in admin.py so editors can create and edit blog posts in the admin interface.
  • A developer uses ModelAdmin to add list_display and search_fields to make the admin list view more useful.
  • A team uses list_filter in ModelAdmin to let admin users quickly filter records by status or category.

More examples

Basic model registration

Registers the Post model with the admin site using the simplest one-line approach.

Example · python
# blog/admin.py
from django.contrib import admin
from .models import Post

admin.site.register(Post)

Customize with ModelAdmin

Uses the @admin.register decorator and ModelAdmin to add list columns, filters, search, and auto-slug.

Example · python
from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ("title", "author", "published_at", "draft")
    list_filter = ("draft", "published_at")
    search_fields = ("title", "body")
    prepopulated_fields = {"slug": ("title",)}

Inline related models

Embeds Comment editing directly inside the Post admin form using a TabularInline.

Example · python
from django.contrib import admin
from .models import Post, Comment

class CommentInline(admin.TabularInline):
    model = Comment
    extra = 1

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    inlines = [CommentInline]

Discussion

  • Be the first to comment on this lesson.