在 model 的 Meta 中定义权限
class Meta:
db_table = 'candidate'
verbose_name = '应聘者'
verbose_name_plural = verbose_name
permissions = [
('export', 'Can export candidate list'),
('notify', 'notify interviewer for candidate review'),
]
因为权限是存在数据库中,所以加完 permissions 后需要进行数据库迁移
python manage.py makemigrations
python manage.py migrate
设置 Admin action 的权限
export_model_as_csv.short_description = '导出为CSV文件'
export_model_as_csv.allowed_permissions = ('export',)
在 has_xxx_permission 设置是否有 xxx 权限
def has_export_permissions(self, request):
opts = self.opts
return request.user.has_perm('%s.%s' % (opts.app_label, "export"))