Django LoginSerializer获取email字段报AttributeError异常问题咨询
Django登录接口AttributeError错误修复方案
根因定位
报错的核心原因是LoginSerializer的validate方法违反了DRF的序列化器规则:
序列化器的validate方法仅允许返回验证完成后的字典数据,或是抛出验证类异常,禁止直接返回Response对象。你调整异常逻辑后,在用户不存在的分支返回了Response实例,该实例会被序列化器当作验证后的数据进行后续字段读取,自然会报'Response'对象没有'email'属性的错误。你之前功能正常就是因为原本用的是抛出异常的逻辑,修改返回方式后才触发问题。
其他待修正的冗余/错误逻辑
- 重复判断:
if not user的判断写在user is None判断之后,永远不会触发,属于无效代码 - 拼写错误:
status.HTTP_401_Unauthorized应为全大写的status.HTTP_401_UNAUTHORIZED - 无效代码:
return super.validate(attrs)写在return语句之后,永远不会执行 - 字段类型不匹配:
tokens字段被定义为CharField,但你自定义的tokens()方法返回的是字典结构,后续会触发类型报错 - 逻辑不统一:部分错误分支返回
Response,部分抛出AuthenticationFailed异常,规则不一致
修复代码
把validate方法中所有返回Response的分支都改成抛出AuthenticationFailed异常即可,你的视图已经配置了serializer.is_valid(raise_exception = True),抛出的异常会被DRF自动处理为符合要求的响应:
class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField() password = serializers.CharField(max_length=68, min_length=6, write_only = True) username = serializers.CharField(read_only=True) # 将tokens字段改为DictField匹配返回结构 tokens = serializers.DictField(read_only=True) class Meta: model=User fields = ['email', 'username', 'password', 'tokens'] def validate(self, attrs): email = attrs.get('email', '') password = attrs.get('password', '') user = auth.authenticate(email=email, password=password) if user is None: raise AuthenticationFailed({'msg':'No such user'}, status=status.HTTP_401_UNAUTHORIZED) if not user.is_active: raise AuthenticationFailed({'msg':'Account is disabled'}) if not user.is_verified: raise AuthenticationFailed({'msg': 'Email is not verified'}) return{ 'email':user.email, 'username':user.username, 'tokens':user.tokens() }
内容的提问来源于stack exchange,提问作者Abinash Karki
相关产品推荐
相关产品推荐

