环境
Python 3.7.6
Django 2.2.16
自定义 Action
admin.py
from django.contrib import admin
from .models import *
@admin.register(People)
class PeoPleAdmin(admin.ModelAdmin):
list_display = ['name', 'sex']
# 显示自定义动作 show action
actions = ['my_custom_action']
# 自定义动作 custom action
def my_custom_action(self, request, queryset):
for obj in queryset:
# 执行代码 do sometings
pass
messages.info(request, '执行完毕。')
# 自定义动作名称 custom action name
my_custom_action.short_description = '自定义动作显示名称'
授予 Action 操作权限
... # 省略 参考:自定义 Action 部分
my_custom_action.short_description = '自定义动作显示名称'
# 授权拥有 change 权限的用户,才可执行 my_custom_action 动作
my_custom_action.allowed_permissions = ('change',)
# 授权拥有 change 或 delete 的用户,才可执行 my_custom_action 动作
my_custom_action.allowed_permissions = ('change', 'delete')
可选权限
add,change,delete,view
自定义 Action 权限
from django.contrib.auth import get_permission_codename
... # 部分省略 参考:自定义 Action 部分
def has_leader_permission(self, request):
# do something
opts = self.opts
codename = get_permission_codename('leader', opts)
return request.user.has_perm('%s.%s' % (opts.app_label, codename))