Registering Models in the Admin
Registering a model shows it in the admin site. The admin lists the model for adding and changing rows.
Register the model
This line goes in admin.py. It shows Post in the admin site.
from django.contrib import admin
from blog.models import Post
admin.site.register(Post)Ask for the admin home page
The admin home page lists the registered models. Posts appears in the list.
client = Client()
client.login(username="sana", password="secret123")
response = client.get("/admin/")
print(response.status_code)
print("Posts" in response.content.decode())Ask for the post list
The change list shows the saved posts. The post appears under its object name.
client = Client()
client.login(username="sana", password="secret123")
response = client.get("/admin/blog/post/")
print(response.status_code)
print("Post object (1)" in response.content.decode())Example
import django
from django.apps import AppConfig
from django.conf import settings
class BlogConfig(AppConfig):
name = "__main__"
label = "blog"
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
INSTALLED_APPS=[
"__main__.BlogConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
],
MIDDLEWARE=[
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": {"context_processors": ["django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages"]}}],
STATIC_URL="/static/",
)
django.setup()
from django.contrib import admin
from django.contrib.auth.models import User
from django.core.management import call_command
from django.db import connection, models
from django.urls import path
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"
with connection.schema_editor() as editor:
editor.create_model(Post)
call_command("migrate", verbosity=0)
User.objects.create_superuser("sana", "sana@example.com", "secret123")
from django.test import Client
admin.site.register(Post)
urlpatterns = [path("admin/", admin.site.urls)]
Post.objects.create(title="First post", body="Hello from Django.")
client = Client()
client.login(username="sana", password="secret123")
response = client.get("/admin/")
print(response.status_code)
print("Posts" in response.content.decode())
response = client.get("/admin/blog/post/")
print(response.status_code)
print("Post object (1)" in response.content.decode())
Key points
- Use admin.site.register() to show a model in the admin.
- Register takes the model class, like admin.site.register(Post).
- A registered model gets an add page and a change list.
- The change list shows one row per saved object.
- A model that is not registered stays out of the admin.
In this example, the setup lines configure Django. The blog app config gives the model an app to live in. A real project keeps the model in a blog app. The program creates the table directly. A real project uses migrations for this step. Register shows Post in the admin site. Migrate builds the tables, and createsuperuser makes the admin account. One create call saves a post. The test client logs in and asks for the admin home page. The prints show 200 and that Posts appears on the page. The last ask fetches the post list. The prints show 200 and that the post appears under its object name.
Note
The admin shows the model under its plural name, Posts.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How do you show Post in the admin site?