Django学习笔记之admin后台管理系统
管理站点
创建一个管理员用户
python manage.py createsuperuser,按提示输入用户名、邮箱、密码
启动服务器,通过“127.0.0.1:8000/admin”访问,输入上面创建的用户名、密码完成登录
进入管理站点,默认可以对groups、users进行管理
管理界面本地化
编辑settings.py
文件,设置编码、时区
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
向admin
注册模型
#----------admin.py---------
from django.contrib import admin
# Register your models here.
from .models import Department,Student,Course
admin.site.register(Department)
admin.site.register(Student)
admin.site.register(Course)
刷新管理页面,可以对数据表中数据进行增删改查操作
自定义管理页面
Django
提供了admin.ModelAdmin
类
通过定义ModelAdmin
的子类,来定义模型在Admin
界面的显示方式
列表页属性
list_display
:显示字段,可以点击列头进行排序
list_filter
:过滤字段,过滤框会出现在右侧
search_fields
:搜索字段,搜索框会出现在上侧
list_per_page
:分页,分页框会出现在下侧
添加、修改页属性
fields
:属性的先后顺序
fieldsets
:属性分组
注意:上面两个属性,二者选一。
例子
#-----models.py------
class Department(models.Model):
d_id = models.AutoField(primary_key=True)
d_name = models.CharField(max_length=30)
def __str__(self):
return 'Department<d_id=%s,d_name=%s>'%(
self.d_id,self.d_name
)
class Student(models.Model):
s_id = models.AutoField(primary_key=True)
s_name = models.CharField(max_length=30)
department = models.ForeignKey('Department')
course = models.ManyToManyField('Course')
def __str__(self):
return 'Student<s_id=%s,s_name=%s>'%(
self.s_id,self.s_name
)
class Course(models.Model):
c_id = models.AutoField(primary_key=True)
c_name = models.CharField(max_length=30)
def __str__(self):
return 'Course<c_id=%s,c_name=%s>'%(
self.c_id,self.c_name
)
# -----------admin.py--------
from django.contrib import admin
# Register your models here.
from .models import Department,Student,Course
class DepartmentAdimin(admin.ModelAdmin):
list_display = ['d_id','d_name'] # 显示字段
list_display_links = ['d_id','d_name'] # 点击可以直接进入修改页面
list_filter = ['d_id'] # 过滤字段
search_fields = ['d_name'] # 搜索字段
class StudentAdimin(admin.ModelAdmin):
list_display = ['s_id','s_name']
list_display_links = ['s_id','s_name']
# fields = ['s_name','course','department']
fieldsets = [ # 属性分组
('第一组',{'fields':['s_name']}),
('第二组',{'fields':['department','course']})
]
class CourseAdmin(admin.ModelAdmin):
list_display = ['c_id','c_name']
list_display_links = ['c_id','c_name']
list_per_page = 5 # 分页,此处5条数据为一页
admin.site.register(Department,DepartmentAdimin) # 注册
admin.site.register(Student,StudentAdimin)
admin.site.register(Course,CourseAdmin)