python - Django休息框架: how to get the current superuser in serialize?

标签 python django superuser

创建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

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

最佳答案

您应该将此 View 限制为仅限 super 用户。创建自定义权限类如下:

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.的信息

关于python - Django休息框架: how to get the current superuser in serialize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67025786/

相关文章:

python - seaborn 热图 pandas 在 isnull 上的计算

python - 在 Keras 上使用 TensorFlow 后端时出现奇怪的输出(OMP : Info #xx KMP_AFFINITY)

python - 当有人评论他们的帖子时如何使用 django-notification 通知用户

python - Django 中的单元测试 : How to initialize database

linux - 特权命令是如何控制的?

python - MySQL:从查询中获取列名或别名

python - 如何在Python Scrapy中的子div中使用特殊的src获取href

python - 如何在 django 模型表单中保存外键

android - 从后台截图并在保存前处理

linux - 在没有 super 用户权限的情况下,Scala shell 无法在 ubuntu 上运行