django-rest-framework - 如何基于 is_staff 为用户创建单独的配置文件

django-rest-framework - How to create seperate profiles for users based on is_staff

我正在做一个工作门户项目。我正在使用自定义用户模型

class UserManager(BaseUserManager):

def create_user(self, email, name, password=None, **extra_fields):

    if not email:
        raise ValueError('Users must have an email address')
    if not name:
        raise ValueError('Users must have a name')

    user = self.model(email=self.normalize_email(email), **extra_fields)
    user.set_password(password)
    user.name = name
    user.save(using=self._db)

    return user

def create_staffuser(self, email, password, name):
    user = self.create_user(
        email,
        name,
        password=password
    )
    user.is_staff = True
    user.save(using=self._db)

    return user

def create_superuser(self,  name, email, password):

    user = self.create_user(email, name, password=password)
    user.is_staff = True
    user.is_superuser = True
    user.save(using=self._db)

    return user

class User(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

我有两个独立的模型,一个是为求职者准备的,另一个是为雇主准备的。

class SeekerProfile(models.Model):
    """Seeker profile for job seekers"""

    MALE = 'M'
    FEMALE = 'F'
    OTHERS = 'O'
    GENDER_CHOICES = [
        (MALE, 'Male'),
        (FEMALE, 'Female'),
        (OTHERS, 'Others'),
    ]
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    date_of_birth = models.DateField()
    gender = models.CharField(
        max_length=1,
        choices=GENDER_CHOICES
    )
    address = models.TextField()
    city = models.CharField(max_length=100)
    pincode = models.CharField(max_length=50)
    phone_number = models.CharField(
        max_length=50, null=False, blank=False, unique=True)
    disabled = models.BooleanField(default=False)
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        limit_choices_to={'is_staff': False},
        on_delete=models.CASCADE
    )

    def __str__(self):
        return self.first_name+" "+self.last_name

class BusinessStream(models.Model):
    """Business Stream dataset database"""

    business_stream_name = models.CharField(max_length=50)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, limit_choices_to={
                             'is_staff': True}, on_delete=models.CASCADE)

class CompanyProfile(models.Model):
    """company profile"""

    user = models.OneToOneField(settings.AUTH_USER_MODEL, limit_choices_to={
        'is_staff': True}, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=100)
    profile_description = models.TextField()
    business_stream = models.ManyToManyField(
        BusinessStream)
    established_date = models.DateTimeField()
    company_url = models.URLField()

我的疑问是如何限制一个用户根据用户模型中的 is_staff 字段为其他类型的用户创建配置文件。

我是django的新手,请帮助我。

views.py

class UserProfileViewSet(ModelViewSet):

    queryset = SeekerProfile.objects.all()
    serializer_class = serializers.ProfileSerializer
    authentication_classes = (JWTAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        """Return objects for the current authenticated user only"""
        queryset = SeekerProfile.objects.filter(user=self.request.user)
        return queryset

    def perform_create(self, serializer):
        return serializer.save(user=self.request.user)

serializers.py

class ProfileSerializer(serializers.ModelSerializer):
    """Serializer for user Profile"""

    class Meta:
        model = SeekerProfile
        fields = '__all__'
        read_only_fields = ('id', 'user')

这允许雇主创建求职者资料。

您必须在您的视图中检查经过身份验证的用户的角色并相应地进行 - s.th。喜欢

class UserProfileViewSet(ModelViewSet):

    queryset = SeekerProfile.objects.all()
    serializer_class = serializers.ProfileSerializer
    authentication_classes = (JWTAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        """Return objects for the current authenticated user only"""
        queryset = SeekerProfile.objects.filter(user=self.request.user)
        return queryset

    def perform_create(self, serializer):
        # Check here
        if self.request.user.is_staff:
             # do something if requesting user is staff
        else:
             # do s.th. else
        return serializer.save(user=self.request.user)