在 model 的 Meta 中定义权限

  1. class Meta:
  2. db_table = 'candidate'
  3. verbose_name = '应聘者'
  4. verbose_name_plural = verbose_name
  5. permissions = [
  6. ('export', 'Can export candidate list'),
  7. ('notify', 'notify interviewer for candidate review'),
  8. ]

因为权限是存在数据库中,所以加完 permissions 后需要进行数据库迁移

  1. python manage.py makemigrations
  2. python manage.py migrate

设置 Admin action 的权限

  1. export_model_as_csv.short_description = '导出为CSV文件'
  2. export_model_as_csv.allowed_permissions = ('export',)

在 has_xxx_permission 设置是否有 xxx 权限

  1. def has_export_permissions(self, request):
  2. opts = self.opts
  3. return request.user.has_perm('%s.%s' % (opts.app_label, "export"))