Django管理后台是一个自动生成的管理界面,让你可以轻松管理应用程序的数据,而无需编写任何额外的代码。
Django管理后台是一个基于Web的界面,它:
基于模型自动创建界面
细粒度的用户权限管理
可自定义界面和功能
安全可靠,适合生产环境
几分钟内获得完整的管理界面
内置认证和权限系统
完全可定制的界面和功能
强大的数据筛选和搜索
首先确保已经运行了数据库迁移,创建必要的表:
python manage.py migrate
这会创建Django内置应用(包括admin)所需的数据库表。
创建一个可以访问管理后台的超级用户:
python manage.py createsuperuser
按照提示输入用户名、邮箱和密码。
运行开发服务器:
python manage.py runserver
在浏览器中访问:
http://127.0.0.1:8000/admin/
使用刚才创建的超级用户凭据登录。
要将模型显示在管理后台中,需要在应用的admin.py文件中进行注册。
最简单的注册方式,使用默认配置:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
from django.contrib import admin
from .models import Post
# 基本注册
admin.site.register(Post)
通过创建 ModelAdmin 类来定制模型的显示方式:
from django.contrib import admin
from .models import Post
# 自定义 ModelAdmin 类
class PostAdmin(admin.ModelAdmin):
# 列表页显示的字段
list_display = ['title', 'created_at', 'is_published']
# 可以点击的字段(链接到编辑页)
list_display_links = ['title']
# 可编辑的字段(无需进入编辑页)
list_editable = ['is_published']
# 右侧过滤器
list_filter = ['created_at', 'is_published']
# 搜索字段
search_fields = ['title', 'content']
# 每页显示的数量
list_per_page = 20
# 注册模型和 ModelAdmin 类
admin.site.register(Post, PostAdmin)
@admin.register 装饰器进行注册(Python 3.7+)list_display 显示最重要的字段list_filter 和 search_fields 提高效率控制模型在列表页的显示方式:
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'created_at',
'is_published', 'short_content']
# 自定义方法字段
def short_content(self, obj):
return obj.content[:50] + '...' if len(obj.content) > 50 else obj.content
# 设置自定义字段的显示名称
short_content.short_description = '内容摘要'
# 排序
ordering = ['-created_at']
# 日期层次导航
date_hierarchy = 'created_at'
控制添加/编辑页面的表单:
class PostAdmin(admin.ModelAdmin):
# 字段分组显示
fieldsets = [
('基本信息', {
'fields': ['title', 'author', 'category']
}),
('内容', {
'fields': ['content', 'tags'],
'classes': ['wide']
}),
('发布设置', {
'fields': ['is_published', 'published_at'],
'classes': ['collapse']
})
]
# 预填充字段
prepopulated_fields = {'slug': ('title',)}
# 选择框优化(外键)
autocomplete_fields = ['author', 'category']
# 只读字段
readonly_fields = ['created_at', 'updated_at']
完整的博客模型管理配置:
from django.contrib import admin
from .models import Post, Category, Tag, Comment
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'category',
'created_at', 'is_published', 'comment_count']
list_filter = ['category', 'is_published', 'created_at']
search_fields = ['title', 'content', 'author__username']
date_hierarchy = 'created_at'
ordering = ['-created_at']
fieldsets = [
(None, {
'fields': ['title', 'author', 'category', 'tags']
}),
('内容', {
'fields': ['content', 'excerpt']
}),
('发布设置', {
'fields': ['is_published', 'published_at'],
'classes': ['collapse']
})
]
filter_horizontal = ['tags']
prepopulated_fields = {'slug': ('title',)}
autocomplete_fields = ['author', 'category']
def comment_count(self, obj):
return obj.comments.count()
comment_count.short_description = '评论数'
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'post_count']
search_fields = ['name']
def post_count(self, obj):
return obj.post_set.count()
post_count.short_description = '文章数'
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ['author', 'post', 'created_at', 'is_approved']
list_filter = ['is_approved', 'created_at']
list_editable = ['is_approved']
search_fields = ['content', 'author__username', 'post__title']
actions = ['approve_comments']
def approve_comments(self, request, queryset):
queryset.update(is_approved=True)
approve_comments.short_description = "批准选中的评论"
Django管理后台允许你定义自定义的批量操作,对选中的多个对象执行特定任务。
创建简单的批量发布操作:
from django.contrib import admin
from django.contrib import messages
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'is_published']
actions = ['make_published', 'make_draft']
def make_published(self, request, queryset):
"""批量发布文章"""
updated = queryset.update(is_published=True)
self.message_user(
request,
f'成功发布了 {updated} 篇文章。',
messages.SUCCESS
)
make_published.short_description = "发布选中的文章"
def make_draft(self, request, queryset):
"""批量设为草稿"""
updated = queryset.update(is_published=False)
self.message_user(
request,
f'成功将 {updated} 篇文章设为草稿。',
messages.SUCCESS
)
make_draft.short_description = "将选中的文章设为草稿"
创建需要用户输入的操作:
from django.contrib import admin
from django.http import HttpResponseRedirect
from django.urls import path
from django.shortcuts import render
class PostAdmin(admin.ModelAdmin):
# ... 其他配置 ...
def get_urls(self):
urls = super().get_urls()
custom_urls = [
path('bulk-feature/', self.bulk_feature_view, name='bulk-feature'),
]
return custom_urls + urls
def bulk_feature_view(self, request):
"""批量设置精选文章"""
if request.method == 'POST':
post_ids = request.POST.getlist('post_ids')
is_featured = request.POST.get('is_featured') == 'on'
# 执行批量更新
Post.objects.filter(id__in=post_ids).update(is_featured=is_featured)
self.message_user(
request,
f'成功更新了 {len(post_ids)} 篇文章的精选状态。',
messages.SUCCESS
)
return HttpResponseRedirect('../')
# 显示选择表单
posts = Post.objects.all()[:10] # 限制显示数量
context = {
'posts': posts,
'opts': self.model._meta,
}
return render(request, 'admin/bulk_feature.html', context)
管理后台包含敏感数据,必须正确配置权限和安全设置。
Django提供了细粒度的权限控制系统:
from django.contrib import admin
from django.contrib.auth.models import User, Group
# 自定义用户管理
class UserAdmin(admin.ModelAdmin):
list_display = ['username', 'email', 'first_name',
'last_name', 'is_staff', 'is_active']
list_filter = ['is_staff', 'is_active', 'groups']
search_fields = ['username', 'first_name', 'last_name', 'email']
filter_horizontal = ['groups', 'user_permissions']
# 限制普通员工用户的权限
def get_queryset(self, request):
qs = super().get_queryset(request)
if not request.user.is_superuser:
# 非超级用户只能看到普通员工用户
return qs.filter(is_staff=True)
return qs
# 重新注册用户模型
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
根据用户权限控制管理后台功能:
class PostAdmin(admin.ModelAdmin):
def get_queryset(self, request):
"""控制用户可见的数据"""
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
# 普通用户只能看到自己创建的文章
return qs.filter(author=request.user)
def get_readonly_fields(self, request, obj=None):
"""控制只读字段"""
if not request.user.has_perm('blog.change_post_status'):
# 没有权限的用户不能修改发布状态
return self.readonly_fields + ['is_published']
return self.readonly_fields
def has_delete_permission(self, request, obj=None):
"""控制删除权限"""
if obj and not request.user.is_superuser:
# 普通用户不能删除已发布的文章
return not obj.is_published
return super().has_delete_permission(request, obj)
DEBUG = FalseALLOWED_HOSTS在父对象的编辑页面直接编辑相关对象:
class CommentInline(admin.TabularInline): # 或 StackedInline
model = Comment
extra = 1 # 默认显示的空表单数量
fields = ['author', 'content', 'created_at']
readonly_fields = ['created_at']
class PostAdmin(admin.ModelAdmin):
inlines = [CommentInline]
创建完全自定义的管理页面:
class PostAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super().get_urls()
custom_urls = [
path('statistics/', self.admin_site.admin_view(
self.statistics_view
), name='post-statistics'),
]
return custom_urls + urls
def statistics_view(self, request):
# 自定义统计页面逻辑
context = {
'title': '文章统计',
'post_count': Post.objects.count(),
'published_count': Post.objects.filter(
is_published=True
).count(),
}
return render(request, 'admin/post_statistics.html', context)
覆盖默认的管理后台模板:
# 在项目的 templates/admin 目录下创建模板文件
# base_site.html - 修改站点标题和头部
# change_list.html - 自定义列表页面
# change_form.html - 自定义表单页面
# index.html - 自定义首页
class PostAdmin(admin.ModelAdmin):
# 使用自定义的变更列表模板
change_list_template = 'admin/blog/post/change_list.html'
# 使用自定义的变更表单模板
change_form_template = 'admin/blog/post/change_form.html'
体验不同配置下的管理后台效果:
| 标题 | 作者 | 发布时间 | 状态 | 操作 |
|---|---|---|---|---|
| Django管理后台使用指南 | admin | 2023-08-01 | 已发布 | |
| Django模型设计最佳实践 | admin | 2023-07-28 | 草稿 |