Django---admin组件使用

激活管理工具

一般我们在生成项目时会在urls.py中自动设置好

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),

]

然后django的管理工具就可以运行了

使用管理工具

启动开发服务器,然后在浏览器中访问 http://127.0.0.1:8000/admin/,得到登陆界面,你可以通过命令 python manage.py createsuperuser 来创建超级用户。

为了让 admin 界面管理某个数据模型,我们需要先注册该数据模型到 admin

from django.db import models

# Create your models here.

class UserInfo(models.Model):
    name=models.CharField(max_length=32)
    pwd=models.CharField(max_length=32)
    email=models.EmailField()
    roles=models.ManyToManyField(to="Role")

    def __str__(self):
        return self.name

class Role(models.Model):
    title=models.CharField(max_length=32)
    permission=models.ManyToManyField(to="Permission")

    def __str__(self):
        return self.title

class Menu(models.Model):
    caption=models.CharField(max_length=32)
    def __str__(self):
        return self.caption

class Permission(models.Model):
    url=models.CharField(max_length=32)
    title=models.CharField(max_length=32)
    permission_group=models.ForeignKey(to="PermissionGroup",default=1)
    code=models.CharField(max_length=32,default="")
    parent=models.ForeignKey("self",null=True,blank=True)

    def __str__(self):
        return self.title

class PermissionGroup(models.Model):
    caption=models.CharField(max_length=32)
    menu=models.ForeignKey(to="Menu",default=1)

    def __str__(self):
        return self.caption
View Code

admin定制

我们在对应的应用下面的admin.py中只需要讲Model中的某个类注册,也就是说在admin中实现增删查改的功能

admin.site.register(models.UserInfo)

但是这种方式比较简单,想要进行更多的操作就要利用ModelAdmin进行操作

方式一:
    class UserAdmin(admin.ModelAdmin):
        list_display = ('user', 'pwd',)
 
    admin.site.register(models.UserInfo, UserAdmin) # 第一个参数可以是列表
     
 
方式二:
    @admin.register(models.UserInfo)                # 第一个参数可以是列表
    class UserAdmin(admin.ModelAdmin):
        list_display = ('user', 'pwd',)

可定制功能

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

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

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]

admin.site.register(UserInfo,UserInfoConfig)

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

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]

    list_display_links = ["name"]
admin.site.register(UserInfo,UserInfoConfig)

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

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

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

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]
    list_editable = ("email",)
   
admin.site.register(UserInfo,UserInfoConfig)

6.search_fileds,列表时,迷糊搜索功能

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]
    
   search_fields = ("name")
admin.site.register(UserInfo,UserInfoConfig)

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

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):
date_hierarchy = 'ctime'
admin.site.register(UserInfo,UserInfoConfig)

 

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中的操作

class  UserInfoConfig(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
admin.site.register(UserInfo,UserInfoConfig)

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.fileds,详细页面时,显示字段的字段

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):
fields = ["name"]
admin.site.register(UserInfo,UserInfoConfig)

13. exclude,详细页面时,排除的字段,也就是和fileds相反,除了这个字段,其余的全显示

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]
    exclude = ["name"]     #和files相反,意思就是除了这个字段,其余字段都展示
   
admin.site.register(UserInfo,UserInfoConfig)

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

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]
    readonly_fields = ["name"]   #只读,只让看不让动
   
admin.site.register(UserInfo,UserInfoConfig)

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

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]
    fieldsets = (
        ('基本数据', {
            'fields': ('name', 'email')
        }),
    
        ('其他', {
            'classes': ('collapse', 'wide', 'extrapretty'),  # 'collapse','wide', 'extrapretty'
            'fields': ('roles',),
        }),
    )
   
admin.site.register(UserInfo,UserInfoConfig)

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

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]
    filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)
   
admin.site.register(UserInfo,UserInfoConfig)

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

from django.contrib import admin

# Register your models here.

from .models import *

class  UserInfoConfig(admin.ModelAdmin):

    list_display = ["id","name","email"]
    ordering = ('-id',)
    或
    def get_ordering(self, request):
        return ['-id', ]
   
admin.site.register(UserInfo,UserInfoConfig)

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

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

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 = "指定列数据为空时,默认显示"

 

posted @ 2018-03-11 17:15  兰博~~  阅读(172)  评论(0编辑  收藏  举报