admin组件使用
Django提供了基于web的管理工具
Django自动管理工具是django.contrib的一部分,可以在项目的settings.py中的 INSTALLED_APPS看到
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "app01" ]
激活管理工具
通常在生成项目时会在urls.py中自动设置好
from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]
使用管理工具
启动开发服务器,然后在浏览器中访问 http://127.0.0.1:8000/admin/, 得到登录界面,可以通过命令 python manage.py createsuperuser 来创建超级用户.
先注册数据模型
from django.db import models # Create your models here. class Author(models.Model): name=models.CharField( max_length=32) age=models.IntegerField() def __str__(self): return self.name class Publish(models.Model): name=models.CharField( max_length=32) email=models.EmailField() def __str__(self): return self.name class Book(models.Model): title = models.CharField( max_length=32) publishDate=models.DateField() price=models.DecimalField(max_digits=5,decimal_places=2) publisher=models.ForeignKey(to="Publish") authors=models.ManyToManyField(to='Author') def __str__(self): return self.title
admin的定制
在admin.py中只需要将model中的某个类注册,即可在admin中实现增删改查的功能,如:
admin.site.register(models.UserInfo)
但是,这种方式比较简单,如果想要进行更多的定制操作,需要利用ModelAdmin进行操作,如:
#方式一: class UserAdmin(admin.ModelAdmin): list_display = ("user", "pwd") admin.site.register(models.UserInfo) #方式二: @admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): list_display = ("user","pwd")
ModelAdmin中提供了大量的可定制的功能,如:
1. list_display 为列表时,定制显示的列(里面不能放多对多字段)
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): list_display = ("user", "pwd", "xxx") def xxx(self, obj): return "xxx"
2. list_display_links 定制列可以点击跳转.(点击后进入编辑页面)
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): list_display = ("user", "pwd", "xxx") 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") list_editable = ("pwd")
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}
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 = "指定列数据为空时,默认显示"
from django.contrib import admin # Register your models here. from .models import * class BookInline(admin.StackedInline): # TabularInline extra = 0 model = Book class BookAdmin(admin.ModelAdmin): list_display = ("title",'publishDate', 'price',"foo","publisher") list_display_links = ('publishDate',"price") list_filter = ('price',) list_editable=("title","publisher") search_fields = ('title',) date_hierarchy = 'publishDate' preserve_filters=False def foo(self,obj): return obj.title+str(obj.price) # 定制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 change_list_template="my_change_list_template.html" class PublishAdmin(admin.ModelAdmin): list_display = ('name', 'email',) inlines = [BookInline, ] admin.site.register(Book, BookAdmin) # 第一个参数可以是列表 admin.site.register(Publish,PublishAdmin) admin.site.register(Author)