gpt4 book ai didi

django - 如何在序列化程序类上获取经过身份验证的用户以进行验证

转载 作者:行者123 更新时间:2023-12-04 09:47:15 26 4
gpt4 key购买 nike

我正在使用django-rest-framework的项目。在我的API View 中,经过身份验证的用户可以创建其他用户。但是,只有五个。然后,如果一个用户注册了五个用户,那么我想在达到限制的响应中将其发送给他。然后,我需要让序列化器成为经过身份验证的用户,但是,我找不到将其从ModelViewSet传递给序列化器的方法。

这是我的代码:

看法:

class ChildUserViewSet(viewsets.ModelViewSet):
serializer_class = ChildUserSerializer
queryset = User.objects.all()

authentication_classes = (
TokenAuthentication,
)
permission_classes = (
IsAuthenticated,
)

def perform_create(self, serializer):
account_group = self.request.user.userprofile.get_account_group

mobile_number = serializer.data.get('mobile_number')
password = serializer.data.get('password')
user = serializer.save()
user.set_password(password)
user.save()

# Generate user profile
UserProfile.objects.create(
user=user,
mobile_number=mobile_number,
user_type=CHILD,
related_account_group=account_group,
)

序列化器:
class ChildUserSerializer(serializers.ModelSerializer):
mobile_number = serializers.CharField()

class Meta:
model = User

fields = (
'first_name',
'last_name',
'email',
'password',
'mobile_number',
)

def validate(self, data):
"""
Check that the start is before the stop.
"""
# Get authenticated user for raise hit limit validation



def validate_email(self, value):
if User.objects.filter(email=value):
raise serializers.ValidationError("This field must be unique.")
return value

def create(self, validated_data):
username = generate_unique_username(
u'{0}{1}'.format(
validated_data['first_name'],
validated_data['last_name'],
)
)

user = User(
username=username,
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
email=validated_data['email'],
)

user.set_password(validated_data['password'])
user.save()

return user

然后,在我的序列化器的 def validate(self, data)函数中,我想要获取当前已认证的用户。

如何将request.user从我的APIView传递给序列化器?

最佳答案

我找到了一种更简单的方法来实现这一目标!事实证明,Rest Framework的GenericAPIView基类(所有Rest Framework的通用View类都从该基类派生而来)includes a function called get_serializer_context() :

def get_serializer_context(self):
"""
Extra context provided to the serializer class.
"""
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}

如您所见,返回的 context对象包含与View接收的相同的 request对象。然后,此对象设置为 when the serializer is initialized:
def get_serializer(self, *args, **kwargs):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
return serializer_class(*args, **kwargs)

因此,要访问发出请求的用户,您只需要从序列化器的 self.context['request'].user函数中调用 validate_:
class TemplateSerializer(serializers.ModelSerializer):
def validate_parent(self, value):
print(self.context['request'].user)

return value

class Meta:
model = Template

最好的部分是,您不必覆盖 ModelViewSet中的任何内容,它们可以像您希望的那样保持简单:
class TemplateViewSet(viewsets.ModelViewSet):
serializer_class = TemplateSerializer
permission_classes = [IsAdmin]

关于django - 如何在序列化程序类上获取经过身份验证的用户以进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29524826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com