admin 组件的使用
Django 提供了基于 web 的管理工具。Django 自动管理工具是 django.contrib 的一部分。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1.apps.App1Config',
]
admin其实就是一个Django封装好的app而已。
admin 组件如何使用:
例:
创建一个adminDemo django 项目时:
1.urls.py 文件会自动创建好:
from django.contrib import admin
from django.urls import path urlpatterns = [
path('admin/', admin.site.urls), ]
2.settings.py文件中:
INSTALLED_APPS=[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1.apps.App1Config', #一般创建项目时,会自动创建这句话,但如果是用命令 python manage.py startapp app1 时,不会自动创建这句配置,需要自己手动添加
#‘app2.apps.App2config’, #或下面那种,直接配置app2
'app2'
]
3.构建自己的模型类
models.py文件中:
from django.db import models # Create your models here.
class Book(models.Model):
title = models.CharField(max_length=32)
pub_date = models.DateField()
price = models.DecimalField(max_digits=5,decimal_places=2)
#publish表和BOOK表为一对多的表,外键关联
publish = models.ForeignKey(to="Publish",on_delete=models.CASCADE)
#BOOK 表和 Author 表为多对多表,此处会创建第3张表
authors = models.ManyToManyField(to="Author",db_table="book2authors") def __str__(self):
return self.title class Publish(models.Model):
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.CharField(max_length=32) def __str__(self): return self.name class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
#作者表和作者详情表示一对一的关系
ad = models.OneToOneField(to="AuthorDetail",null=True,on_delete=models.CASCADE)
def __str__(self):
return self.name class AuthorDetail(models.Model): birthday = models.DateField()
telephone = models.BigIntegerField()
addr = models.CharField(max_length=64) def __str__(self):
return str(self.telephone)
models.py
4.在app1(或app2) admin.py文件中:
from django.contrib import admin # Register your models here. from .models import Publish,Author,AuthorDetail,Book from django.utils.safestring import mark_safe class Bookconfig(admin.ModelAdmin):
#自定义列
def show_authors(self,obj):
print(obj.authors.all()) return ",".join([obj.name for obj in obj.authors.all() ])#作者那列通过循环显示,用逗号分开
#要显示的列
list_display = ["title","price","show_authors",'pub_date',"publish"]
search_fields = ["title","price"] #按字段搜索
# list_editable = ["price"] #设置某个字段可编辑
list_filter = ["publish"]#通过出版社查或分类,一般一对多和多对多用该方法
ordering = ["-price"] #按价格从大到小排列
# change_list_template = "mylist.html"
#多选批量初始化
def patch_init(self,request,queryset):
queryset.update(price=100)
patch_init.short_description = "批量初始化"
# actions = ["patch_init"]
actions = [patch_init] class PublishConfig(admin.ModelAdmin):
list_display = ["name","city",'email']
list_display_links = ["city","email"] #默认第一个字段为超链接, 此处自定义超链接字段 #在admin.py中只需要讲Mode中的某个类注册,即可在Admin中实现增删改查的功能
#注册admin.site
admin.site.register(Book,Bookconfig)
admin.site.register(Author)
admin.site.register(AuthorDetail)
admin.site.register(Publish,PublishConfig)
5.创建超级管理用户:
通过命令 python manage.py createsuperuser 来创建超级用户,设置用户名,密码和邮箱,访问 http://127.0.0.1:8000/admin/,输入这个账号和密码,就可以进入
admin 给模型类创建好的页面。
输入刚创建好的超级用户名和密码后:
admin的定制
在admin.py中只需要讲Mode中的某个类注册,即可在Admin中实现增删改查的功能,如:
admin.site.register(models.UserInfo)
想要进行更多的定制操作,需要利用ModelAdmin进行操作:
方式一:
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd',) admin.site.register(models.UserInfo, UserAdmin) # 第一个参数可以是列表 方式二:
@admin.register(models.UserInfo) # 第一个参数可以是列表
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd',)
1. list_display,列表时,定制显示的列。
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd', 'xxxxx') def xxxxx(self, obj):
return "xxxxx"
2. list_display_links,列表时,定制列可以点击跳转。
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd', 'xxxxx')
list_display_links = ('pwd',)
3. list_filter,列表时,定制右侧快速筛选。
4. list_select_related,列表时,连表查询是否自动select_related
5. list_editable,列表时,可以编辑的列
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd','ug',)
list_editable = ('ug',)
6. search_fields,列表时,模糊搜索的功能
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin): search_fields = ('user', 'pwd')
7. date_hierarchy,列表时,对Date和DateTime类型进行搜索
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin): date_hierarchy = 'ctime'
8 inlines,详细页面,如果有其他表和当前表做FK,那么详细页面可以进行动态增加和删除
class UserInfoInline(admin.StackedInline): # TabularInline
extra = 0
model = models.UserInfo class GroupAdminMode(admin.ModelAdmin):
list_display = ('id', 'title',)
inlines = [UserInfoInline, ]
9 action,列表时,定制action中的操作
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin): # 定制Action行为具体方法
def func(self, request, queryset):
print(self, request, queryset)
print(request.POST.getlist('_selected_action')) func.short_description = "中文显示自定义Actions"
actions = [func, ] # Action选项都是在页面上方显示
actions_on_top = True
# Action选项都是在页面下方显示
actions_on_bottom = False # 是否显示选择个数
actions_selection_counter = True
10 定制HTML模板
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None
11 raw_id_fields,详细页面,针对FK和M2M字段变成以Input框形式
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin): raw_id_fields = ('FK字段', 'M2M字段',)
12 fields,详细页面时,显示字段的字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
fields = ('user',)
13 exclude,详细页面时,排除的字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
exclude = ('user',)
14 readonly_fields,详细页面时,只读字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
readonly_fields = ('user',)
15 fieldsets,详细页面时,使用fieldsets标签对数据进行分割显示
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
fieldsets = (
('基本数据', {
'fields': ('user', 'pwd', 'ctime',)
}),
('其他', {
'classes': ('collapse', 'wide', 'extrapretty'), # 'collapse','wide', 'extrapretty'
'fields': ('user', 'pwd'),
}),
)
16 详细页面时,M2M显示时,数据移动选择(方向:上下和左右)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)
17 ordering,列表时,数据排序规则
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
ordering = ('-id',)
或
def get_ordering(self, request):
return ['-id', ]
18. radio_fields,详细页面时,使用radio显示选项(FK默认使用select)
radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL
19 form = ModelForm,用于定制用户请求时候表单验证
from app01 import models
from django.forms import ModelForm
from django.forms import fields class MyForm(ModelForm):
others = fields.CharField() class Meta:
model = models = models.UserInfo
fields = "__all__" @admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin): form = MyForm
20 empty_value_display = "列数据为空时,显示默认值"
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
empty_value_display = "列数据为空时,默认显示" list_display = ('user','pwd','up') def up(self,obj):
return obj.user
up.empty_value_display = "指定列数据为空时,默认显示"
例子2:admin.py中:
from django.contrib import admin # Register your models here.
#导入当前文件夹中,某文件中的类 from .models import Book,Publish,AuthorDetail,Author
from django.utils.safestring import mark_safe
#admin 的定制 ,
class Bookconfig(admin.ModelAdmin): def show_authors(self,obj):
return [obj.name for obj in obj.authors.all()] list_display_links = ["price",] def delbtn(self):
return "删除"
def a_link(self):
return "<a>删除</a>" def b_link(self):
return mark_safe("<a>删除</a>") list_display = ["title", "price", "publish", "pub_date", "show_authors",delbtn,a_link,b_link] # 展现书的名字 #给模型类注admin
admin.site.register(Book,Bookconfig)
admin.site.register(Publish)
admin.site.register(Author)
admin.site.register(AuthorDetail)
效果:
知识点补充:
from app1 import models
1.models.Book._meta.model_name
得到模型类 名的小写:'book'
2.models.Book._meta.app_label
得到模型类所在app 小写名 :'app1'
admin 组件源码解析过程:
admin源码解析:
1 启动所有app下的admin.py文件
autodiscover_modules('admin', register_to=site)
2 注册模型类 admin.site: AdminSite的单例对象
admin.site.register(Book,BookConfig)
admin.site.register(Author) class ModelAdmin():
pass class AdminSite(): def __init():
self._registry = {} # model_class class -> admin_class instance def register(self, model_or_iterable, admin_class=None):
admin_class = admin_class or ModelAdmin
self._registry[model] = admin_class(model, self) 3 基于二级分发设计url路由
path('index/', views.index),
path('index/',([
path('test01/', test01),
path('test02/', test02),
],None,None)), # 二级分发 path('index/',([
path('name/', ([
path('alex/', test01),
path('egon/', test02),
],None,None)),
path('shop/', ([
path('apple/', test03),
path('xiaomi/', test04),
path('huawei/', test05),
],None,None)),
],None,None)),
二级分发的应用:
初始 分发原理: path("index",视图函数)或 path( "index" , ( get_urls(), None , None) ) #admin 中 的: def get_urls(): tmp =[ ] for model, config_obj in admin.site._registry.items(): model_name=model._meta.model_name app_label = model._meta.app_label tmp.append( path("%s/%s/"%(app_label,model_name),config_obj.urls) ) return tmp #增删改查视图函数,此函数可以放在 模型类对应的配置类中放此函数 def get_urls(self): tmp=[ path(" " ,self.list_view ), path("add/'',self.add_view), path( "(\d+)/change/" , self.change_view ) path( "(\d+)/delete/", self.delete_view ) ] return tmp @property
def urls(self):
return self.get_urls(),NOne,None)