Implement roles in django rest framework

后端 未结 2 1097
梦谈多话
梦谈多话 2021-02-09 06:48

I am building an API that should have the following kind of users

super_user - create/manage admins

admin - manage events(model) and ev

2条回答
  •  孤街浪徒
    2021-02-09 07:01

    So in Django any user has a flag is_superuser that corresponds to your 'superuser'. So just use that - e.g. User.objects.create(is_superuser=True).

    For the rest you can simply use a field for a normal User model to differentiate between subroles of a normal user.

    class User(AbstractBaseUser):
        can_participate_event = models.Boolean(default=False)
        can_create_event = models.Boolean(default=False)
    

    Or

    class User(AbstractBaseUser):
        permissions = models.CharField(default='')  # and populate with e.g. 'create_event,participate_event'
    

    Still you will need to check all those fields in your view probably. The more you add to your application, the hairier this becomes so I would suggest using a 3rd party library like rest-framework-roles (I'm the author) or guardian.

提交回复
热议问题