Django内置Admin
Admin
使用Django Admin
1. admin 是app
2. admin
url(r'^$', wrap(self.index), name='index'),
url(r'^login/$', self.login, name='login'),
url(r'^logout/$', wrap(self.logout), name='logout'),
url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True),name='password_change_done'),
3. app01/models.py
from django.db import models
class UserInfo(models.Model):
user = models.CharField(max_length=32)
email = models.EmailField()
4. app01/admin.py #注册用户自己的类 生成URL
from django.contrib import admin
from app01 import models
admin.site.register(models.UserInfo)
//根据注册的类 admin.site.register(models.UserInfo) 生成URL
//http://127.0.0.1:8001/admin/app01/userinfo/ - 数据列表
//http://127.0.0.1:8001/admin/app01/userinfo/add/ - 添加数据
//http://127.0.0.1:8001/admin/app01/userinfo/1/change/ - 修改数据
//http://127.0.0.1:8001/admin/app01/userinfo/1/delete/ - 删除数据
{
models.UserInfo: admin.ModelAdmin(models.UserInfo,admin.site)
models.UserGroup: admin.ModelAdmin(models.UserGroup,admin.site)
}
ModelAdmin中提供可定制功能
1. list_display,列表时,定制显示的列
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
models.py from django.db import models class UserGroup(models.Model): title = models.CharField(max_length=32) class UserInfo(models.Model): user = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.user 事例一: (显示类的列) admin.py from django.contrib import admin from app01 import models from django.http import HttpResponse class UserInfoModelAdmin(admin.ModelAdmin): list_display = ('user','email') #自定义页面 # def changelist_view(self, request, extra_context=None): # return HttpResponse("....") admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin) 事例二: (自定义类的列) from django.contrib import admin from app01 import models from django.http import HttpResponse class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return "%s-%s" % (obj.user,obj.email,) list_display = ('user','email',自定义) admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin) 事例三: (自定义类的列, a 链接 ) #导入from django.utils.safestring import mark_safe from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin)
2. list_display_links,列表时,定制列可以点击跳转 (默认是第一列)
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
# 原先 <a> 在user上 现在在email上 from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) list_display_links = ('email',) admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin)
3. list_filter,列表时 定制右侧快速筛选
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) list_filter = ('user','email') admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin)
4. list_select_related,列表时 连表查询是否自动select_related
5. 分页相关
# 分页,每页显示条数
list_per_page = 100
# 分页,显示全部(真实数据<该值时,才会有显示全部)
list_max_show_all = 200
# 分页插件
paginator = Paginator
6. list_editable 列表时 可以编辑的列
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd','ug',)
list_editable = ('ug',)
7. search_fields 列表时 模糊搜索的功能
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
# 根据user筛选 from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) search_fields = ('user',) admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin)
8. date_hierarchy 列表时 对Date和DateTime类型进行搜索
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
# models.py 类里需要有时间列 from django.db import models # Create your models here. class UserGroup(models.Model): title = models.CharField(max_length=32) class UserInfo(models.Model): user = models.CharField(max_length=32) email = models.EmailField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user # admin.py from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) date_hierarchy = 'date' admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin)
9. preserve_filters 详细页面 删除、修改,更新后跳转回列表后,是否保留原搜索条件
10. save_as = False 详细页面 按钮为“Sava as new” 或 “Sava and add another”
11. save_as_continue = True 点击保存并继续编辑
save_as_continue = True
# 如果 save_as=True,save_as_continue = True, 点击Sava as new 按钮后继续编辑。
# 如果 save_as=True,save_as_continue = False,点击Sava as new 按钮后返回列表。
New in Django 1.10.
12. save_on_top = False 详细页面,在页面上方是否也显示保存删除等按钮
13. inlines,详细页面,如果有其他表和当前表做FK,那么详细页面可以进行动态增加和删除
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) class UserInfoInline(admin.TabularInline): # TabularInline StackedInline extra = 0 model = models.UserInfo class UserGroupModelAdmin(admin.ModelAdmin): list_display = ('id', 'title',) inlines = [UserInfoInline, ] admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,UserGroupModelAdmin) admin.site.register(models.Role,admin.ModelAdmin)
14. action 列表时 定制action中的操作
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) # 定制Action行为具体方法 def func(self, request, queryset): print(self, request, queryset) print(request.POST.getlist('_selected_action')) func.short_description = "操作" actions = [func, ] # Action选项都是在页面上方显示 #actions_on_top = True # Action选项都是在页面下方显示 #actions_on_bottom = False # 是否显示选择个数 #actions_selection_counter = True admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin)
15. 定制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
16. raw_id_fields 详细页面 针对FK和M2M字段变成以Input框形式
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) raw_id_fields = ('ug',) admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin)
17. fields 详细页面时 显示字段的字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
fields = ('user',)
18. exclude 详细页面时 排除的字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
exclude = ('user',)
19. readonly_fields 详细页面时 只读字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
readonly_fields = ('user',)
20. 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'),
}),
)
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) fieldsets = ( ('基本数据', { 'fields': ('user',) }), ('其他', { 'classes': ('collapse', 'wide', 'extrapretty'), # 'collapse','wide', 'extrapretty' 'fields': ('email',), }), ) admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin)
21. 详细页面时 M2M显示时 数据移动选择(方向:上下和左右)
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
# models.py from django.db import models class UserGroup(models.Model): title = models.CharField(max_length=32) class Role(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name class UserInfo(models.Model): user = models.CharField(max_length=32) email = models.EmailField() date = models.DateTimeField(auto_now_add=True) ug = models.ForeignKey(UserGroup,null=True,blank=True) m2m = models.ManyToManyField('Role') def __str__(self): return self.user # admin.py from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) raw_id_fields = ('ug',) filter_vertical = ('m2m',) # 或filter_horizontal = ("m2m字段",) admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin) admin.site.register(models.Role,admin.ModelAdmin)
22. ordering 列表时 数据排序规则
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
ordering = ('-id',)
或
def get_ordering(self, request):
return ['-id', ]
23. view_on_site 编辑时 是否在页面上显示view on set
view_on_site = False
或
def view_on_site(self, obj):
return 'https://www.baidu.com'
24. radio_fields 详细页面时 使用radio显示选项(FK默认使用select)
radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) radio_fields = {"ug": admin.VERTICAL} admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin) admin.site.register(models.Role,admin.ModelAdmin)
25. show_full_result_count = True 列表时 模糊搜索后面显示的数据个数样式
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from django.contrib import admin from app01 import models from django.http import HttpResponse from django.utils.safestring import mark_safe class UserInfoModelAdmin(admin.ModelAdmin): def 自定义(obj): # obj 每行的一个对象 return mark_safe("<a href='http://www.baidu.com'>%s</a>" % (obj.user,)) list_display = ('user','email',自定义) search_fields = ('user',) show_full_result_count = True admin.site.register([models.UserInfo],UserInfoModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin) admin.site.register(models.Role,admin.ModelAdmin)
26. formfield_overrides = {} 详细页面时 指定现实插件
from django.forms import widgets
from django.utils.html import format_html
class MyTextarea(widgets.Widget):
def __init__(self, attrs=None):
# Use slightly better defaults than HTML's 20x2 box
default_attrs = {'cols': '40', 'rows': '10'}
if attrs:
default_attrs.update(attrs)
super(MyTextarea, self).__init__(default_attrs)
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
return format_html('<textarea {}>\r\n{}</textarea>',final_attrs, value)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
formfield_overrides = {
models.models.CharField: {'widget': MyTextarea},
}
27. prepopulated_fields = {} 添加页面 当在某字段填入值后 自动会将值填充到指定字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
prepopulated_fields = {"email": ("user","pwd",)}