Skip to content
Advertisement

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

I am working on a job portal project. I am using custom user model

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']

And I have 2 separate models one for job seekers and other for employers.

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()

My doubt is how to restrict one user from creating a profile on other type of user based on is_staff field in User model.

I am new to django, please help me.

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')

This allows employer to create seeker profile.

Advertisement

Answer

You would have to check the role of the authenticated user in your view and proceed accordingly – s.th. like

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)
8 People found this is helpful
Advertisement