Django Rest Framework: how to get the current superuser in serialize?

Viewed 353

CreateApiView :

class CreateEmployeeApiView(generics.CreateAPIView):
# authentication_classes = [TokenAuthentication, SessionAuthentication, ]
permission_classes = [IsAuthenticated]
queryset = Employee.objects.all()
serializer_class = CreateEmployeeApiSerializer

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

and serializer :

class CreateEmployeeApiSerializer(serializers.ModelSerializer):
# user = serializers.HiddenField(default=serializers.CurrentUserDefault())
username = serializers.CharField(source='user.username', required=True)
email = serializers.EmailField(source='user.email', required=True)
password = serializers.CharField(source='user.password',
                                 style={'input_type': 'password', 'placeholder': 'Password'},
                                 write_only=True, required=True)

     class Meta:
         model = Employee
         fields = (
             'username',
             'email',
             'password',
             'is_delete',
             'first_name',
             'last_name',
             'father_name',
             'birth',
             'avatar',
             'status',
         )

     def to_representation(self, instance):
         data = super(CreateEmployeeApiSerializer, self).to_representation(instance)
         status = instance.status
         data['status'] = Employee.USER_ROLE[status - 1][1]
         data['author'] = instance.author.username
         data['user'] = instance.user.username
         return data

     def create(self, validated_data):
         # Create new user
         print(validated_data)
         user = User.objects.create(username=validated_data['user']['username'],
                               email=validated_data['user']['email'])
         user.set_password(validated_data['user']['password'])
         user.save()

         # Create employee
         # super_user = User.objects.filter(is_superuser=True)
         employee = Employee(user=user)
         employee.is_delete = validated_data['is_delete']
         employee.first_name = validated_data['first_name']
         employee.last_name = validated_data['last_name']
         employee.first_name = validated_data['first_name']
         employee.father_name = validated_data['father_name']
         employee.birth = validated_data['birth']
         employee.avatar = validated_data['avatar']
         employee.status = validated_data['status']
         employee.author = user
         employee.save()
         return employee

I need a superuser, not a simple user. When employee is created, the employee.author field must be assigned by the logged in user (i.e. the current superuser). How should I do it? I hope you understood me correctly!

2 Answers

You should restrict this view to only superusers. Create custom permission class as below:

from rest_framework.permissions import BasePermission


class IsSuperUser(BasePermission):
    """
    Allows access only to superusers.
    """

    def has_permission(self, request, view):
        return bool(request.user and request.user.is_superuser)

And in your view:

permission_classes = (IsSuperUser,)

Read more about permissions in DRF.

In the view class, you can get the current user with request.user. You will need to pass this into your serializer in order to set the author.

Related