让我们有一个我的用户模型的结构。
BaseUser <- BusinessOwner <- Business Staff (BusinessOwner can create,update,delete BusinessStaff )
BaseUser <- Customer
从 AbstractBaseUser 创建继承用户时遇到问题,我只想在表中添加一行,其中myappname_baseuser_user_permissions
包含列:id
、、、正确的权限分配给正确的用户,例如:、、baseuser_id
permission_id
id
add_staff
change_staff
delete_staff
当我使用管理页面创建新的 BusinessOwner 用户并轻松添加权限时,事情是正常的,但不是我使用 django restframework 的 POST 方法,没有权限。那么我应该把我的权限代码放在哪里?什么是代码?在model.py
或view.py
?,我的权限代号是 : add_staff
, change_staff
, anddelete_staff
这是我的model.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)
我的观点.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()
和我的serializers.py
class CreateBusinessOwner(serializers.ModelSerializer):
class Meta:
model = BusinessOwner
fields = ('email', 'password', 'first_name', 'last_name', 'business_name' ,'date_joined')
read_only_fields = ('date_joined',)
谢谢你帮助我!