如何使用Django restframework从AbstractBaseUser设置继承的User模型的权限

时间:2014-05-12 21:03:00

标签: django django-models django-rest-framework django-authentication django-permissions

让我的用户模型结构。

BaseUser <- BusinessOwner <- Business Staff (BusinessOwner can create,update,delete BusinessStaff )
BaseUser <- Customer

从AbstractBaseUser创建继承用户时遇到问题,我想要的是在myappname_baseuser_user_permissions表中添加一行,其中包含列:idbaseuser_id,{{1 },并将正确的权限分配给正确的用户permission_id,例如:idadd_staffchange_staff

当我使用管理员页面创建新的BusinessOwner用户并轻松添加权限时,这是正常的,但不是使用django restframework的POST方法,没有权限。那么我应该在哪里放置我的权限代码?什么是代码?在delete_staffmodel.py? ,我的权限代号为:view.pyadd_staffchange_staff

这是我的delete_staff

model.py

我的view.py

class UserManager(BaseUserManager):
    def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):

    now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email,
                is_staff=is_staff, is_active=True,
                is_superuser=is_superuser, last_login=now,
                date_joined=now, **extra_fields)
    user.set_password(password)
    user.save(using=self._db)
    return user

    def create_user(self, email, password=None, **extra_fields):
        return self._create_user(email, password, False, False,
                             **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(email, password, True, True,
                             **extra_fields)

class BaseUser(AbstractBaseUser, PermissionsMixin):
    first_name=models.CharField(max_length=20)
    last_name=models.CharField(max_length=20)
    email=models.EmailField(max_length=254, unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')



class BusinessOwner(BaseUser):
    business_name=models.CharField(max_length=20)

class Customer(BaseUser):
    address=models.CharField(max_length=30)

class Staff(BaseUser):
    position=models.CharField(max_length=30)

和我的serializers.py

class CreateBusinessOwnerView(mixins.ListModelMixin,
              mixins.CreateModelMixin,
              generics.GenericAPIView):
    queryset = BusinessOwner.objects.all()
    serializer_class = CreateBusinessOwner

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def post_save(self, obj, created=False):
        if created:
            obj.set_password(obj.password)
            obj.save()

感谢您的帮助!

0 个答案:

没有答案