gpt4 book ai didi

django - 以编程方式创建具有权限的 django 组

转载 作者:行者123 更新时间:2023-11-28 19:35:27 26 4
gpt4 key购买 nike

在管理控制台中,我可以添加一个组并添加一系列与我的模型相关的权限,例如

api | project | Can add project
api | project | Can change project
api | project | Can delete project

我如何以编程方式执行此操作。我找不到有关如何执行此操作的任何信息。

我有:

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

from api.models import Project


new_group, created = Group.objects.get_or_create(name='new_group')
# Code to add permission to group ???
ct = ContentType.objects.get_for_model(Project)
# Now what - Say I want to add 'Can add project' permission to new_group?

更新:感谢您提供的答案。我能够用它来计算出我需要的东西。就我而言,我可以执行以下操作:

new_group, created = Group.objects.get_or_create(name='new_group')
proj_add_perm = Permission.objects.get(name='Can add project')
new_group.permissions.add(proj_add_perm)

最佳答案

使用下面的代码

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from api.models import Project
new_group, created = Group.objects.get_or_create(name='new_group')
# Code to add permission to group ???
ct = ContentType.objects.get_for_model(Project)

# Now what - Say I want to add 'Can add project' permission to new_group?
permission = Permission.objects.create(codename='can_add_project',
name='Can add project',
content_type=ct)
new_group.permissions.add(permission)

关于django - 以编程方式创建具有权限的 django 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22250352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com