2017-08-23 16 views
8

これで、Djangoグループモジュールを使用して新しいグループを作成できます。 from django.contrib.auth.models import Group グループに権限を割り当てることができます。たとえば、私は新しいグループ "HR"djangoでどのように動的にパーミッションを作成できますか?

によってGroup(name="HR")を作成しました。

今、私は私が他のグループにこの権限を割り当てることができすべき

  • can_create_hr
  • can_edit_hr

などの権限を作成します。

どうすればいいですか?

答えて

1

権限を直接作成してグループに割り当てることもできます。ただ、許可を作成するには、別のグループにこの権限を割り当てたい場合は、単にアクセス許可オブジェクトを取得し、同じように割り当てるグループ

from django.contrib.auth.models import User, Group, Permission 
from django.contrib.contenttypes.models import ContentType 

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.get(name='HR') 
group.permissions.add(permission) 

に権限を追加します。

permission = Permission.objects.get(codename='can_create_hr') 
group= Group.objects.get(name='some_name') 
group.permissions.add(permission) 

あなたは空白の移行を作成した場合、あなたは(答え上記からの借入)このような何かを行うことができdocs

1

でそれについての詳細を読むことができます:

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) 
    ] 
関連する問題