为何验证OTP时出现AttributeError: 'NoneType'对象无'email'属性?
OTP验证代码错误分析与修复
你的问题出在当OTP错误时,查询结果result是None,但代码直接访问了result.email,导致触发AttributeError。
具体原因
当用户输入的邮箱和OTP组合在数据库中不存在时,Otp.objects.filter(email=email, otp_no=otp_no).first()会返回None。这时候你直接执行len(result.email),相当于在None对象上调用email属性,自然会报错。
修复后的代码
@api_view(['POST']) def verifyOtp(request): email = request.data.get('email') otp_no = request.data.get('otp_no') res = dict() if email and otp_no: # 简化非空判断,None和空字符串都会被视为False result = Otp.objects.filter(email=email, otp_no=otp_no).first() if result: # 先判断查询结果是否存在 res['isOtpVerified'] = True return JsonResponse(res) else: # 邮箱+OTP组合不存在,可能是OTP错误或邮箱未发送过OTP res['isOtpVerified'] = False res['message'] = "邮箱或OTP验证码错误" return JsonResponse(res) else: # 邮箱或OTP为空的情况 res['error'] = "邮箱和OTP验证码不能为空" return JsonResponse(res)
关键优化点
- 先判断
result是否存在,再访问其属性,避免None对象的属性调用错误 - 简化了非空判断逻辑,
if email and otp_no比if email!= None and otp_no!= None更简洁 - 移除了冗余的
otp_no == result.otp_no判断,因为filter已经确保了查询结果的otp_no和输入一致 - 补充了参数为空的处理逻辑,让接口的错误反馈更全面
内容的提问来源于stack exchange,提问作者Ritika
相关产品推荐
相关产品推荐

