我想向组添加(已经存在,通过元标记中的权限定义)权限并寻找正确的位置。我必须确保在 sync_db 命令之后,所有组都分配了正确的权限。
我想连接一个 post_syncdb 信号,但信号文档说:
重要的是,该信号的处理程序执行幂等更改(例如,不更改数据库),因为如果刷新管理命令也在 syncdb 命令期间运行,这可能会导致刷新管理命令失败。
因此,可能不建议有人在通过 sync_db_post 信号调用的管理命令中向组添加权限。
我计划像这样设置权限:
class UserProfile(models.Model):
user = models.OneToOneField(User)
company = models.ForeignKey(Company, related_name='user_profiles')
department = models.ForeignKey(Department, related_name='user_profiles')
class Meta:
permissions = (
('admin_section_access', 'Access to front-end admin section'),
)
在管理命令中:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
args = 'none'
help = 'Sets the defined group permissions'
def handle(self, *args, **options):
front_end_admin_group, created = Group.objects.get_or_create(name="Front End Admin")
#get the content type for the UserProfile model
user_profile_ct = ContentType.objects.get(app_label='organization', model='userprofile')
admin_section_access_perm = Permission.objects.get(content_type=user_profile_ct, codename="admin_section_access")
front_end_admin_group.permissions.add(admin_section_access_perm)
self.stdout.write('Successfully setup group permissions.')