Admin站点管理:
概述:
内容发布:负责添加,修改,删除内容的
公告访问
配置Admin应用:
在settings.py文件中的INSTALLED_APPS中添加'django.contrib.admin',
这条默认是添加好的。
创建管理员用户:
在项目目录下执行 python manage.py createsuperuser
依次输入账号名,邮箱,密码即可完成用户创建
登陆:
http://127.0.0.1:8000/admin/
汉化:
把project\settings.py
中作如下设定:LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
管理数据表:
修改 myAPP\admin.py 如下:
from django.contrib import admin
# Register your models here.
from .models import Grades, Students
# 注册
admin.site.register(Grades)
admin.site.register(Students)
自定义管理页面:
属性说明
# 列表页属性
list_display = [] # 显示字段设置
list_filter = [] # 过滤字段设置
search_fields = [] # 搜索字段设置
list_per_page = [] # 分页设置
# 添加,修改页属性
fields = [] # 规定属性的先后顺序
fieldsets = [] # 给属性分组 注意:fields与fieldsets不能同时使用
属性示例:
# 列表页属性
list_display = ['pk', 'gname', 'gdate', 'ggirlnum', 'gboynum', 'isDelete']
list_filter = ['gname']
search_fields = ['gname']
list_per_page = 5
# 添加,修改页属性
# fields = ['ggirlnum', 'gboynum', 'gname', 'gdate', 'isDelete']
fieldsets = [
("num",{"fields":['ggirlnum', 'gboynum']}),
("base", {"fields":["gname", "gdate", "isDelete"]}),
]
关联对象:需求:在创建一个班级时可以直接添加几个学生
class StudentsInfo(admin.TabularInline):# 可选参数admin.StackedInline
model = Students
extra = 2
class GradesAdmin(admin.ModelAdmin):
inlines = [StudentsInfo]
布尔值显示问题示例:
class StudentsAdmin(admin.ModelAdmin):
def gender(self):
if self.sgender:
return "男"
else:
return "女"
# 设置页面列的名称
gender.short_description = "性别"
list_display = ['pk', 'sname', 'sage', gender,
'scontend', 'sgrade', 'isDelete']
list_per_page = 10
admin.site.register(Students, StudentsAdmin)
执行按钮位置:
class StudentsAdmin(admin.ModelAdmin):
...snip...
actions_on_top = False
actions_on_bottom = True
admin.site.register(Students, StudentsAdmin)
使用装饰器完成注册:
@admin.register(Students)
class StudentsAdmin(admin.ModelAdmin):
def gender(self):
...snip...
actions_on_top = False
actions_on_bottom = True