如何在django中动态创建权限?

时间:2017-08-23 06:13:42

标签: python django

现在我可以使用Django组模块创建新组。 from django.contrib.auth.models import Group 我可以为组分配权限。例如,我创建了一个新组 “HR”

Group(name="HR")

现在我想创建像

这样的权限
  • can_create_hr
  • can_edit_hr

我应该可以将此权限分配给其他群组。

我该怎么做?

3 个答案:

答案 0 :(得分: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 :(得分:1)

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

Error: Cannot find module './src/ParseError' from '/home/bianca/Documents/CS/supersecret/supersecret_/node_modules/katex/dist'
at /home/bianca/.nvm/versions/node/v7.5.0/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:55:21
at load (/home/bianca/.nvm/versions/node/v7.5.0/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:69:43)
at onex (/home/bianca/.nvm/versions/node/v7.5.0/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:92:31)
at /home/bianca/.nvm/versions/node/v7.5.0/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:22:47
at FSReqWrap.oncomplete (fs.js:112:15)

答案 2 :(得分:0)

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, Group ,Permission

class Role(models.Model):
    role=models.CharField(max_length=50,unique=True)
    groups = models.ManyToManyField(Permission)

    def __str__(self):
        return str(self.role)

    # def ___init__(self, name):
    #     self.name = role

class User(AbstractBaseUser):
    email =models.EmailField(max_length=225,unique=True)
    name =models.CharField(max_length=225)
    created = models.DateTimeField(auto_now_add=True)
    is_active=models.BooleanField(default=True)
    role=models.ForeignKey(Role,on_delete=models.CASCADE,default=0)

    USERNAME_FIELD ='email'
    REQUIRED_FIELDS=['username']

更多访问[此处]:https://github.com/jocavinashi/Dynamic-role-in-Django-rest-framework