【问题标题】:Django Rest Framework: how to get the current superuser in serialize?Django Rest Framework:如何在序列化中获取当前超级用户?
【发布时间】:2021-04-09 17:32:43
【问题描述】:

创建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 字段必须由登录用户(即当前超级用户)分配。我该怎么做?我希望你能正确理解我!

【问题讨论】:

  • 如果当前登录的用户不是超级用户,你想做什么?

标签: python django superuser


【解决方案1】:

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

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.

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 2021-11-21
      • 2016-10-03
      • 2022-01-17
      • 2022-11-22
      • 1970-01-01
      • 2015-07-24
      • 2018-11-21
      相关资源
      最近更新 更多