• Django之 admin组件


    本节内容

    • 路由系统
    • models模型
    • admin 
    • views视图
    • template模板

    Django Admin介绍

    admin 是django 自带的用来让你进行数据库管理的web app. 
    提供了很多定制化功能,你甚至可以用它来进行公司内部的内容管理

    启用admin

    你用startproject命令创建项目时django admin就默认启用了

    For reference, here are the requirements:

    1. Add 'django.contrib.admin' to your INSTALLED_APPS setting.
    2. The admin has four dependencies - django.contrib.auth, django.contrib.contenttypes, django.contrib.messages and django.contrib.sessions. If these applications are not in your INSTALLED_APPS list, add them.
    3. Add django.contrib.auth.context_processors.auth and django.contrib.messages.context_processors.messages to the 'context_processors' option of the DjangoTemplates backend defined in your TEMPLATES as well as django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware to MIDDLEWARE. These are all active by default, so you only need to do this if you’ve manually tweaked the settings.
    4. Determine which of your application’s models should be editable in the admin interface.

    admin 访问地址

    http://localhost:yourport/admin/, by default.

    为什么会让登录?哪来的用户信息?django自带了一套用户认证系统,admin就用了这个, 所以你想登录,先创建管理员账号。

    1
    python manage.py createsuperuser

    然后你就开心的登录进去了呀

    发现只有这么个东西, 什么东东?

    这就是django自带的用户认证系统的2张表,用于管理账户和账户组信息。

    那接下来要干什么呢? 注意django admin的作用是让你管理各app下的数据库表,实现可以通过Web页面就完成对数据的增删改查噢。 admin不会没事闲的自己把你创建的表拿过来管理,你得把你写的表在admin里注册一下才行。 

    在每个app下有个admin.py文件 ,在那里面注册你想要被管理的表

    1
    2
    3
    4
    5
    6
    7
    8
    9
    from django.contrib import admin
     
    # Register your models here.
     
    from app01 import models
     
     
    admin.site.register(models.Article)
    admin.site.register(models.Account)

    然后刷新下页面,新添加的2个表就出来了  

    admin定制

    你可以定义每张表显示哪些字段、对某些字段进行过滤、允许搜索等功能,这就需要定制一下admin的类了

    1
    2
    3
    4
    class ArticleAdmin(admin.ModelAdmin):
        list_display = ('title','pub_date','account','read_count')
         
    admin.site.register(Article, ArticleAdmin)

    一下子就好看了,真是神奇呀。

    就喜欢你这没见识的样子,别急,还有很多nb的功能呢,一起来看下。

    看来这个list_display就是定义表数据要展示哪些字段的,除了这个属性,admin 还提供了哪些其它功能呢?

    fields 决定对表进行修改时展示哪些字段

    1
    2
    3
    class ArticleAdmin(admin.ModelAdmin):
        list_display = ('title','pub_date','account','read_count')
        fields = ['title','account','pub_date']

    还可以多个字段显示在一行。

    1
    fields = ['title','account',('pub_date','read_count')]

    exclude 不展示哪些字段  

    date_hierarchy = 'pub_date'  按日期分类显示数据  

    You can also specify a field on a related model using the __ lookup, for example:
    date_hierarchy = 'author__pub_date'

    fieldsets 分组显示

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class ArticleAdmin(admin.ModelAdmin):
        list_display = ('title','pub_date','account','read_count')
        date_hierarchy = 'pub_date'
     
        fieldsets = (('文章相关',{
            'fields':('title','content'),
            'classes': ('wide''extrapretty'),
        }),('高级',{
            'classes':('collapse',),
            'fields':(('account','read_count'),'pub_date')
        }))

    上面的classes 是用于设定字段样式,2个默认自带的样式是collapse 和wide

    filter_horizontal,filter_vertical 均用于多对多字段 

    1
    filter_horizontal = ['tags',]

     

    list_display  定义表数据显示哪些列

    除了表中有的字段,models自己定义的字段也能放入list_display

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    from django.db import models
    from django.contrib import admin
     
    class Person(models.Model):
        name = models.CharField(max_length=50)
        birthday = models.DateField()
     
        def decade_born_in(self):
            return self.birthday.strftime('%Y')[:3+ "0's"
        decade_born_in.short_description = 'Birth decade'
     
    class PersonAdmin(admin.ModelAdmin):
        list_display = ('name''decade_born_in')

    甚至还能玩出花样  

    from django.utils.html import format_html
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <br>class Tag(models.Model):
        """文章标签表"""
        name = models.CharField(max_length=64,unique=True)
        date = models.DateTimeField(auto_now_add=True)
        color_code = models.CharField(max_length=6)
     
        def colored_name(self):
            return format_html(
                '<span style="color: #{};">{}</span>',
                self.color_code,
                self.name,
            )
     
        def __str__(self):
            return self.name
    1
    2
    class TagAdmin(admin.ModelAdmin):
        list_display = ['name','colored_name']

    竟然出现了样式,神奇。

      

    list_display_links = ('first_name', 'last_name') 点下这2个字段就跳到修改页

    list_filter 过滤,把要过滤的字段放到对应列表里就可以

    1
    list_filter = ('register_date',)

      

    list_per_page = 20 每页显示20条数据

      

    radio_fields 把外键或choice字段由下拉框变成单选框

    1
    2
    3
    4
    5
    class ArticleAdmin(admin.ModelAdmin):
        list_display = ('title','pub_date','account','read_count')
        date_hierarchy = 'pub_date'
        filter_horizontal = ['tags',]
        radio_fields = {'account': admin.VERTICAL}

    自动补全

    autocomplete_fields = ['account',] 自动补全,外键查询数据多时,方便查找  

    raw_id_fields  言语无法表示的字段

    就把外键变成这样子

    readonly_fields = ('address_report',)  只读字段

    search_fields  模糊查找

    1
    search_fields = ['account__username','title']

      

    好啦,就先讲这些吧, 当然admin还有很多更高级的功能,不过先会这些就够了,以后会深入再讲的。  

  • 相关阅读:
    微服务实战(二):使用API Gateway
    微服务实战(一):微服务架构的优势与不足
    在WIN7、WIN10操作系统用WebDAV映射网络驱动器需要的操作
    docker开机启动和docker-compose开机启动执行相应的各个docker容器
    /etc/rc.d/init.d自启动程序说明
    C# 通过反射实现对象映射:将2个属性相近的对象相互转换
    添加windows右键菜单:使用exe应用程序打开文件/文件夹
    .NET5 MVC Program.cs 笔记
    前端 JS 正则表达式积累
    VS Code 快捷键
  • 原文地址:https://www.cnblogs.com/shuai1991/p/11186942.html
Copyright © 2020-2023  润新知