细说Django的admin

简介: 在admin.py中只需要将地Model中某个类注册,即可在Admin中进行增删查改的功能,例如:admin.site.register(models.UserInfo)这种方式比较简单,如果想要进行更多的定制操作,就需要利用ModelAdmin进行操作方式一 from django.

admin.py中只需要将地Model中某个类注册,即可在Admin中进行增删查改的功能,例如:

admin.site.register(models.UserInfo)

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

方式一

    from django.contrib import admin
    from . import models
    
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish')
        
    admin.site.register(models.Book,BookAdmin)

没有设置BookAdmin时,系统默认为ModelAdmin

models.Book实际上是一个列表,也可以写成

    from django.contrib import admin
    from . import models
    
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish')
        
    admin.site.register([models.Book,],BookAdmin)

这个参数里可以写多个表名,但要注意的是这里面添加的表名都必须要有list_display中声明要显示的字段

方式二

from django.contrib import admin
from . import models

@admin.register(models.Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ('title','price','publish')

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

定制admin

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish')

在后台管理页面中,显示书的名称,价格以及出版社等信息

img_eb147166961349ed970776542d260b21.png

在class类中还有如下用法:

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','aaa')
    
        def aaa(self,obj):
            return obj.title+"--aaaa"

显示如下

img_74de129fb68d7bd4e9df4d2ee9a781ad.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish')
        list_display_links = ('title','price','publish')

在后台页面显示的时候,所显示的列为可以点击跳转

img_83f5e028e5f090ffa398575bd58189a2.png

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

例子一:

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
    
        list_display = ('title','price','publish')
        list_filter = ('classification','publish')

效果如下:

img_e2e93e04bbafe026a6747261c5401661.png

例子二:

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish')
    
        class Ugg(admin.SimpleListFilter):
    
            title=uget('类型')
    
            parameter_name = "book"
    
            def lookups(self, request, model_admin):
                """
                显示筛选选项,列出价格大于100的书箱的类型
                :param request:
                :param model_admin:
                :return:
                """
                return models.Book.objects.filter(price__gt=100).values_list("publish","classification")
    
            def queryset(self, request, queryset):
                """
                点击查询时,进行筛选
                :param request:
                :param queryset:
                :return:
                """
                v1=self.value()
                return queryset
    
        list_filter = ["publish",Ugg,]
    

效果如下:

img_b45b6b94bc901142aafe73df0cc57eef.png

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

使用联表查询可以提高数据库的查询性能

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish')
    
        list_select_related = ["publish"]   # 联表查询出版社的信息
    

5. 分页相关

list_per_page=10            # 分页,每页显示的数据条数
list_max_show_all=100       # 分页,显示全部数据时,最多显示的数据条数
paginator=Paginator         # 分布插件

例如:

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
    
        list_display = ('title','price','publish')
        list_per_page = 2

效果如下:

img_ad495a88e3237c728694f8a27fc61d44.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish')
    
        list_editable = ('price','publish')
    

效果如下:

img_ecfed5169642caad595077ec79237bfa.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish')
    
        list_select_related = ["publish"]
    
        search_fields = ['title','classification']

效果如下:

img_fe5b9072e098bac8c0b280af1c467d0a.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish','publication_date')
    
        list_select_related = ["publish"]
    
        date_hierarchy="publication_date"

效果如下:

img_2b291d3c93b6e5d63de127a6fc9bf692.png

img_ad3d944bf2ba7f8d079eaba46623552b.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish','publication_date')
    
        list_select_related = ["publish"]
    
        search_fields = ['title', 'classification']
    
        preserve_filters=True

效果如下:

img_d3e28ed48461d85258562a83d12d7213.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish','publication_date')
    
        list_select_related = ["publish"]
    
        save_as = True

效果如下:

img_5dc1d868bd5876ed68d6133793e57606.png

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish','publication_date')
    
        list_select_related = ["publish"]
    
        save_as = False

效果如下:

img_d14bdf6138cd6f515bba82d3e67d0e2c.png

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

用法与上一个用法相同

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish','publication_date')
    
        list_select_related = ["publish"]
    
        save_on_top = False

效果如下:

img_af553a81614a1cfc1955e8a539dd5ce3.png

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','publish','publication_date')
    
        list_select_related = ["publish"]
    
        save_on_top = True
        

效果如下:

img_270136d5772ae45b3c0c6ac8ed6d10f0.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price')
    
    
    class BookInline(admin.StackedInline):
        extra=0
        model=models.Book
    
    class PublishAdmin(admin.ModelAdmin):
        inlines = [BookInline,]
        list_display = ['name','addr']
    
    admin.site.register(models.Publish,PublishAdmin)
    

效果如下:

img_2d00b4bf359dcee3bc690515ec1b1c79.png

在编辑或添加出版社的时候可以同时添加多本书箱数据,添加书籍信息的时候是纵向添加书籍信息的

在这里BookInline这个类还可以继承TabularInline这个类实现横向添加书籍信息

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price')
    
    
    class BookInline(admin.TabularInline):
        extra=0
        model=models.Book
    
    class PublishAdmin(admin.ModelAdmin):
        inlines = [BookInline,]
        list_display = ['name','addr']
    
    admin.site.register(models.Publish,PublishAdmin)
    

效果如下:

img_ad38c59d4ebaf271b4264f180da2829b.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price')
    
        def func1(self,request,queryset):       # 定义具体的action的方法
            pass
    
        func1.short_description = "自定义操作"   # 在页面上显示方法的名称
    
        actions_on_top = True                   # action在页面上方显示
    
        actions_on_bottom = False               # action在页面下方显示
    
        actions_selection_counter = True        # 显示页面上选择数据的条数
    
        actions=[func1,]                        # 添加定制的action的操作
    

在action列表中,添加一个func1的功能

img_9737d5b19583152f98a5f36eb6dd7c1e.png

15. 定制HTML模板

Django后台管理页面默认使用的模板是change_list.html

img_095558792358bada7529fbdc6343793a.png

打开change_list.html页面,添加一行

    <h3>hello python</h3>

刷新浏览器,可以看到

img_719294d420235c27c75a6988719eea9f.png

可以设置的选项有:

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                  # 有ForeignKey时关联数据进行处理的模板

例子:

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price')
    
        change_list_template = ['change_list1.html']
        

效果如下:

img_517c53db4130963fdcff61e6a413c746.png

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

正常显示的时候,FKM2M字段是通过下拉框来进行操作的

添加raw_id_fields配置后,针对FKM2M字段变成以Input框形式

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ('title','price','classification')
    
        raw_id_fields = ('publish','authors')

效果如下:

img_386e5f0bd0b20780eb11df3e034c35de.png

img_a628355e38416b119fe5af099c1caae8.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        
        fields = ('title','price')
        

效果如下:

img_1cd1c4a8a3628084373f944e1661ac86.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
    
        exclude = ('classification',)

效果如下:

img_cff7593acf1f661c3dffeb68d7f7a52c.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        
        readonly_fields = ('classification',)
        

效果如下:

img_1ff6d92755913df3bac58c3b654db760.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
    
        fieldsets = (
            ("基本信息",{
                "fields":("title","price","publish",)
            }),
            ("出版信息",{
            "classes":("collapse","wide","extrapretty"),
            "fields":("classification","authors","publication_date",)
        }),
        )
        

效果如下:

img_032af457d645e45d0197f3af6ac54345.png

img_d5710d2477edd7977fc1409326940e6a.png

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

from django.contrib import admin
from . import models

@admin.register(models.Book)
class BookAdmin(admin.ModelAdmin):

    filter_vertical = ("authors",)
    

效果如下:

img_cad1a77bcd02d461ef0b999b3d90965f.png

from django.contrib import admin
from . import models

@admin.register(models.Book)
class BookAdmin(admin.ModelAdmin):

    filter_horizontal = ("authors",)
    

效果如下:

img_26e60fa47fb694fc434f1a90f99366e8.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ("title","price","classification","publish")
    
        ordering=("-price",)

效果如下:

img_bb0c87bdd0adf06e89d03ad6e8d7142c.png

from django.contrib import admin
from . import models

@admin.register(models.Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ("title","price","classification","publish")

    ordering=("price",)

效果如下:

img_a564622ee7bf19e2adfd8e4f032bbc18.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ("title","price","classification","publish")
    
        def view_on_site(self,obj):
    
            return "http://www.baidu.com"

点击view on set按钮,浏览器会指向"http://www.baidu.com"

img_a1d845156b6793de58514e12f56b952d.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ("title","price","classification","publish")
    
        radio_fields = {"publish":admin.VERTICAL}

效果如下:

img_2c03ebbe9ec13430a704f84b7a46eeb2.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ("title","price","classification","publish")
    
        search_fields = ('title','classification')
    
        show_full_result_count = True

效果如下:

img_28c796588c16453e3c48cc71e6314dcb.png

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

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ("title","price","classification","publish")
    
        search_fields = ('title','classification')
    
        prepopulated_fields = {"title":("classification",)}

效果如下:

img_fcae712a4b9e0cc0ff68f65a0df7104b.png

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

未进行配置之前:

img_5f430b625fa2c85cd8cce4e734eacfe7.png

修改配置文件:

    from django.contrib import admin
    from . import models
    from django.forms import ModelForm
    
    class MyForm(ModelForm):
        class Meta:
            model=models.Book
            fields="__all__"
            error_messages = {
                "title": {'required': "书名不能为空"},
                "price": {'required': "价格不能为空"}
            }  # 自定义错误信息,用户输入错误时显示
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ("title","price","classification","publish")
    
        search_fields = ('title','classification')
    
        form=MyForm

效果如下:

img_3df52c3339d27af2a59a9919c0ec82dc.png

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

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ("title","price","classification","publish")
    
        search_fields = ('title','classification')
    
        empty_value_display="列数据为空时,默认显示"

总结:

  • 在定制admin的所有的操作的时候都是在配置文件中完成的.
  • 在配置文件中,可以进行配置的有数据表的字段,函数和类
  • 在某个页面中,可以配置使用自定义的模板.
  • 同样的,请求到达Django的时候,也可以配置使其执行自定义的函数

ModelAdmin是放置在options.py文件中的.

打开options.py文件,可以看到ModelAdmin里有一个叫做changelist_view的方法

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Book)
    class BookAdmin(admin.ModelAdmin):
        list_display = ("title","price","classification","publish")
    
        search_fields = ('title','classification')
    
        empty_value_display="列数据为空时,默认显示"

可以看到,BookAdmin是继承自ModelAdmin这个类的,ModelAdmin里有一个changelist_view 的方法

所以在BookAdmin中也可以自定义一个changelist_view的视图函数.

自定义了changelist_view后,changelist_view这个方法只能对BookAdmin类生效,对别的类不起作用

目录
相关文章
|
1月前
|
数据管理 数据库 数据安全/隐私保护
Django——Auth模块以及admin站点
Django——Auth模块以及admin站点
|
2月前
|
Python
百度搜索:蓝易云【Django自带的Admin后台中如何获取当前登录用户】
在上面的代码中,`@staff_member_required`装饰器确保只有管理员可以访问 `my_custom_view`视图,而 `@login_required`装饰器确保只有登录的用户可以访问该视图。然后,可以使用 `request.user.username`获取当前登录用户的用户名,并将其传递到模板中进行显示或其他操作。
40 3
|
2月前
|
人工智能 开发工具 数据库
Django实践-03模型-02基于admin管理表
Django实践-03模型-02基于admin管理表
Django实践-03模型-02基于admin管理表
|
8月前
|
数据安全/隐私保护 Python
27 Django高级- Admin站点
27 Django高级- Admin站点
45 0
|
11月前
|
Linux Python
django -- admin里的配置
django -- admin里的配置
|
12月前
|
数据库 数据安全/隐私保护 Python
08-Django-基础篇-admin管理后台
08-Django-基础篇-admin管理后台
|
XML 关系型数据库 MySQL
【Django】当大型项目采用Django框架对于QueryDict以及模板的表单在Admin 管理工具的使用
【Django】当大型项目采用Django框架对于QueryDict以及模板的表单在Admin 管理工具的使用
149 0
【Django】当大型项目采用Django框架对于QueryDict以及模板的表单在Admin 管理工具的使用
|
数据可视化 数据库 Python
Django(7)Admin管理工具(二)
Django(7)Admin管理工具(二)
125 0
Django(7)Admin管理工具(二)
|
关系型数据库 MySQL 项目管理
Django(7)Admin管理工具(一)
Django(7)Admin管理工具(一)
183 0
Django(7)Admin管理工具(一)
|
中间件 数据库 Python
【Django知识补充 - 1】:admin站点和rest_framework实现文件的上传和下载
【Django知识补充 - 1】:admin站点和rest_framework实现文件的上传和下载
275 0
【Django知识补充 - 1】:admin站点和rest_framework实现文件的上传和下载