如何在Django中动态创建权限? [英] How can dynamically create permission in django?

查看:75
本文介绍了如何在Django中动态创建权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我可以使用Django组模块创建新组。 django.contrib.auth.models导入组中的

我可以为组分配权限。例如,我通过 Group(name = HR) HR

Now I can create new groups using Django group module. from django.contrib.auth.models import Group I can assign permissions to group. For example I created a new group "HR"

>。

现在我想创建权限


  • can_create_hr

  • can_edit_hr

我应该能够将此权限分配给其他组。

I should able to assign this permission to other groups.

我该怎么办?

推荐答案

如果创建空白迁移,则可以执行某些操作像这样(从上面的答案中借用):

If you create a blank migration, you can do something like this (borrowing from above answer):

def create_groups_and_permissions(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    ContentType = apps.get_model('contenttypes', 'ContentType')
    Permission = apps.get_model('auth', 'Permission')
    emit_post_migrate_signal(2, False, 'default')  # this creates default permissions (in case this migration was run simultaneously with the creation of relevant models and you need to grab those perms)
    content_type = ContentType.objects.get(app_label='app_name', model='model_name')
    permission = Permission.objects.create(codename='can_create_hr',
                                   name='Can create HR',
                                   content_type=content_type) # creating permissions
    group = Group.objects.filter(name='HR')
    group.permissions.add(permission)

class Migration(migrations.Migration):
    dependencies = [
        ('lsoa', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_groups_and_permissions)
    ]

这篇关于如何在Django中动态创建权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆