• 框架----Django内置Admin


    Django内置的Admin是对于model中对应的数据表进行增删改查提供的组件,使用方式有:

     1 依赖APP:
     2         django.contrib.auth
     3         django.contrib.contenttypes
     4         django.contrib.messages
     5         django.contrib.sessions
     6 
     7     模板的context_processors:
     8         django.contrib.auth.context_processors.auth
     9         django.contrib.messages.context_processors.messages
    10 
    11     中间件:
    12         django.contrib.auth.middleware.AuthenticationMiddleware 
    13         django.contrib.messages.middleware.MessageMiddleware
    Django Admin内部依赖

    一、配置路由

    1 urlpatterns = [
    2         url(r'^admin/', admin.site.urls),
    3     ]

    当前配置的路由可以创建一些路由映射关系:

    /admin/
    /admin/login/
    /admin/logout/
    /admin/password_change/
    /admin/password_change/done/

    /admin/app名称/model名称/
    /admin/app名称/model名称/add/
    /admin/app名称/model名称/ID值/history/
    /admin/app名称/model名称/ID值/change/
    /admin/app名称/model名称/ID值/delete/

    二、定制Admin

    在admin.py中只需要讲Mode中的某个类注册,即可在Admin中实现增删改查的功能,如:

    1 admin.site.register(models.UserInfo)

    但是,这种方式比较简单,如果想要进行更多的定制操作,需要利用ModelAdmin进行操作,如:

     1 方式一:
     2     class UserAdmin(admin.ModelAdmin):
     3         list_display = ('user', 'pwd',)
     4  
     5     admin.site.register(models.UserInfo, UserAdmin) # 第一个参数可以是列表
     6      
     7  
     8 方式二:
     9     @admin.register(models.UserInfo)                # 第一个参数可以是列表
    10     class UserAdmin(admin.ModelAdmin):
    11         list_display = ('user', 'pwd',)

    ModelAdmin中提供了大量的可定制功能,如

    1. list_display,列表时,定制显示的列。

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     list_display = ('user', 'pwd', 'xxxxx')
    4  
    5     def xxxxx(self, obj):
    6         return "xxxxx"

    2. list_display_links,列表时,定制列可以点击跳转。

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     list_display = ('user', 'pwd', 'xxxxx')
    4     list_display_links = ('pwd',)

    3. list_filter,列表时,定制右侧快速筛选。

     1 from django.utils.translation import ugettext_lazy as _
     2  
     3 @admin.register(models.UserInfo)
     4 class UserAdmin(admin.ModelAdmin):
     5     list_display = ('user', 'pwd')
     6  
     7     class Ugg(admin.SimpleListFilter):
     8         title = _('decade born')
     9         parameter_name = 'xxxxxx'
    10  
    11         def lookups(self, request, model_admin):
    12             """
    13             显示筛选选项
    14             :param request:
    15             :param model_admin:
    16             :return:
    17             """
    18             return models.UserGroup.objects.values_list('id', 'title')
    19  
    20         def queryset(self, request, queryset):
    21             """
    22             点击查询时,进行筛选
    23             :param request:
    24             :param queryset:
    25             :return:
    26             """
    27             v = self.value()
    28             return queryset.filter(ug=v)
    29  
    30     list_filter = ('user',Ugg,)

    4. list_select_related,列表时,连表查询是否自动select_related

    5. 分页相关

    1 # 分页,每页显示条数
    2     list_per_page = 100
    3  
    4 # 分页,显示全部(真实数据<该值时,才会有显示全部)
    5     list_max_show_all = 200
    6  
    7 # 分页插件
    8     paginator = Paginator

    6. list_editable,列表时,可以编辑的列

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     list_display = ('user', 'pwd','ug',)
    4     list_editable = ('ug',)

    7. search_fields,列表时,模糊搜索的功能

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3      
    4     search_fields = ('user', 'pwd')

    8. date_hierarchy,列表时,对Date和DateTime类型进行搜索

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3  
    4     date_hierarchy = 'ctime'

    9. preserve_filters,详细页面,删除、修改,更新后跳转回列表后,是否保留原搜索条件

    10. save_as = False,详细页面,按钮为“Sava as new” 或 “Sava and add another”

    11. save_as_continue = True,点击保存并继续编辑

    1 save_as_continue = True
    2  
    3 # 如果 save_as=True,save_as_continue = True, 点击Sava as new 按钮后继续编辑。
    4 # 如果 save_as=True,save_as_continue = False,点击Sava as new 按钮后返回列表。
    5  
    6 New in Django 1.10.

    12. save_on_top = False,详细页面,在页面上方是否也显示保存删除等按钮

    13. inlines,详细页面,如果有其他表和当前表做FK,那么详细页面可以进行动态增加和删除

    1 class UserInfoInline(admin.StackedInline): # TabularInline
    2     extra = 0
    3     model = models.UserInfo
    4  
    5  
    6 class GroupAdminMode(admin.ModelAdmin):
    7     list_display = ('id', 'title',)
    8     inlines = [UserInfoInline, ]

    14. action,列表时,定制action中的操作

     1 @admin.register(models.UserInfo)
     2 class UserAdmin(admin.ModelAdmin):
     3  
     4     # 定制Action行为具体方法
     5     def func(self, request, queryset):
     6         print(self, request, queryset)
     7         print(request.POST.getlist('_selected_action'))
     8  
     9     func.short_description = "中文显示自定义Actions"
    10     actions = [func, ]
    11  
    12     # Action选项都是在页面上方显示
    13     actions_on_top = True
    14     # Action选项都是在页面下方显示
    15     actions_on_bottom = False
    16  
    17     # 是否显示选择个数
    18     actions_selection_counter = True

    15. 定制HTML模板

    1 add_form_template = None
    2 change_form_template = None
    3 change_list_template = None
    4 delete_confirmation_template = None
    5 delete_selected_confirmation_template = None
    6 object_history_template = None

    16. raw_id_fields,详细页面,针对FK和M2M字段变成以Input框形式

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3  
    4     raw_id_fields = ('FK字段', 'M2M字段',)

    17. fields,详细页面时,显示字段的字段

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     fields = ('user',)

    18. exclude,详细页面时,排除的字段

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     exclude = ('user',)

    19. readonly_fields,详细页面时,只读字段

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     readonly_fields = ('user',)

    20. fieldsets,详细页面时,使用fieldsets标签对数据进行分割显示

     1 @admin.register(models.UserInfo)
     2 class UserAdmin(admin.ModelAdmin):
     3     fieldsets = (
     4         ('基本数据', {
     5             'fields': ('user', 'pwd', 'ctime',)
     6         }),
     7         ('其他', {
     8             'classes': ('collapse', 'wide', 'extrapretty'),  # 'collapse','wide', 'extrapretty'
     9             'fields': ('user', 'pwd'),
    10         }),
    11     )

    21. 详细页面时,M2M显示时,数据移动选择(方向:上下和左右)

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)

    22. ordering,列表时,数据排序规则

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     ordering = ('-id',)
    4 5     def get_ordering(self, request):
    6         return ['-id', ]

    23. view_on_site,编辑时,是否在页面上显示view on set

    1 view_on_site = False
    2 3 def view_on_site(self, obj):
    4     return 'https://www.baidu.com'

    24. radio_fields,详细页面时,使用radio显示选项(FK默认使用select)

    1     
    2 radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL

    25. show_full_result_count = True,列表时,模糊搜索后面显示的数据个数样式

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     # show_full_result_count = True # 1 result (12 total)
    4     # show_full_result_count = False  # 1 result (Show all)
    5     search_fields = ('user',)

    26. formfield_overrides = {},详细页面时,指定现实插件

     1 from django.forms import widgets
     2 from django.utils.html import format_html
     3  
     4 class MyTextarea(widgets.Widget):
     5     def __init__(self, attrs=None):
     6         # Use slightly better defaults than HTML's 20x2 box
     7         default_attrs = {'cols': '40', 'rows': '10'}
     8         if attrs:
     9             default_attrs.update(attrs)
    10         super(MyTextarea, self).__init__(default_attrs)
    11  
    12     def render(self, name, value, attrs=None):
    13         if value is None:
    14             value = ''
    15         final_attrs = self.build_attrs(attrs, name=name)
    16         return format_html('<textarea {}>
    {}</textarea>',final_attrs, value)
    17  
    18  
    19  
    20 @admin.register(models.UserInfo)
    21 class UserAdmin(admin.ModelAdmin):
    22  
    23     formfield_overrides = {
    24         models.models.CharField: {'widget': MyTextarea},
    25     }

    27. prepopulated_fields = {},添加页面,当在某字段填入值后,自动会将值填充到指定字段。

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3  
    4     prepopulated_fields = {"email": ("user","pwd",)}

    PS: DjangoAdmin中使用js实现功能,页面email字段的值会在输入:user、pwd时自动填充

    28. form = ModelForm,用于定制用户请求时候表单验证

     1 from app01 import models
     2 from django.forms import ModelForm
     3 from django.forms import fields
     4  
     5  
     6 class MyForm(ModelForm):
     7     others = fields.CharField()
     8  
     9     class Meta:
    10         model = models = models.UserInfo
    11         fields = "__all__"
    12  
    13 @admin.register(models.UserInfo)
    14 class UserAdmin(admin.ModelAdmin):
    15  
    16     form = MyForm

    29. empty_value_display = "列数据为空时,显示默认值"

    1 @admin.register(models.UserInfo)
    2 class UserAdmin(admin.ModelAdmin):
    3     empty_value_display = "列数据为空时,默认显示"
    4  
    5     list_display = ('user','pwd','up')
    6  
    7     def up(self,obj):
    8         return obj.user
    9     up.empty_value_display = "指定列数据为空时,默认显示"
  • 相关阅读:
    深入了解Java ClassLoader、Bytecode 、ASM、cglib (I)
    如何在ant里import
    敏捷练习(1)评估我的生活方向盘
    你是一个合格的孩子吗?
    [转] C# 路径(目录)
    XML学习记录
    js学习总结不断更新(1)
    LINQ TO XML练习
    做技术,切不可沉湎于技术
    js学习总结持续更新(2)
  • 原文地址:https://www.cnblogs.com/wangyongsong/p/7485607.html
Copyright © 2020-2023  润新知