gpt4 book ai didi

django rest JSONWebTokenAPIView 序列化器类对象没有属性 'object'

转载 作者:行者123 更新时间:2023-12-04 17:40:37 25 4
gpt4 key购买 nike

我正在将 JSONWebTokenAPIView 从 rest_framework_jwt 扩展到我的自定义 View :

class UserLogin(JSONWebTokenAPIView):

serializer_class = serializers.AdabaziUserLoginJWT

这是我的自定义序列化器类:

class AdabaziUserLoginJWT(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField(style = {'input-type':'password'})
status = serializers.SerializerMethodField(method_name='show_status')
#token = serializers.CharField(read_only=True)

class Meta():
model = Adabazi_user
fields = ('status')

def show_status(self,obj):
return obj.status

def validate(self,attrs):

credentials={
'username' : attrs.get('username'),
'password' : attrs.get('password')
}

user = authenticate(**credentials)
if user :
if user.is_active:
ada_user = Adabazi_user.objects.get(user=user)
if ada_user.status ==1:
ada_user.status = 2 #user is logged in right now
ada_user.updated_at = timezone.now()
user.last_login = timezone.now()
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return {
'token':token,
'user':user,
'adabazi_user' : ada_user}
else:
raise serializers.ValidationError('User is already logged in.')
else:
raise serializers.ValidationError('Account is deactivated.')
else:
raise serializers.ValidationError('User credentials failed.')

def create(self,validated_data):
user = validated_data['user']
adabazi_user = validated_data['adabazi_user']
user.save()
ada_user.save()
return ada_user

但是当我想POST usernamepasswordlocalhost/api/user/login/ 时此网址与我的观点相关联;发生此错误:

在这行代码中,JSONWebTokenAPIView的post方法报错user = serializer.object.get('user') or request.user

Exception Value: 'AdabaziUserLoginJWT' object has no attribute 'object'


如何访问序列化程序实例对象属性?序列化程序是否有任何对象属性?

最佳答案

我最近遇到了同样的错误,看起来问题出在 rest_framework_jwt 库和 rest_framework 本身的集成:rest_framework_jwt 似乎还没有用 rest_framework 的最新版本更新,而 rest_framework 的序列化器中的代码发生了变化(参见 here)。

rest_framework 的新版本中,没有像 serializer.object.get 这样的语法,因为:

Previously the serializers used a two-step object creation, as follows:

Validating the data would create an object instance. This instance would be >available as serializer.object. Calling serializer.save() would then save the object instance to the database.

We now use single-step object creation, like so:

Validating the data makes the cleaned data available as serializer.validated_data. Calling serializer.save() then saves and returns the new object instance.

因此,为了使用此类,您必须使用 rest_framework 的新 API 更新它。

关于django rest JSONWebTokenAPIView 序列化器类对象没有属性 'object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54645096/

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