Django Rest Framework:如何在序列化中获取当前超级用户?

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

创建ApiView :

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)

和序列化程序:

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

我需要一个超级用户,而不是一个简单的用户。创建员工时,employee.author 字段必须由登录用户(即当前超级用户)分配。我应该怎么做?希望您理解正确!

在视图class中,您可以使用request.user获取当前用户。您需要将其传递到您的序列化程序中才能设置 author.

您应该将此视图限制为仅超级用户。创建自定义权限 class 如下:

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)

在您看来:

permission_classes = (IsSuperUser,)

阅读更多关于 permissions in DRF.