You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自定义登录输入错误凭证触发AssertionError问题求助

Django登录验证AssertionError问题排查与解决

问题现象

输入错误登录凭证时,程序抛出AssertionError,错误信息如下:

AssertionError at /accounts/login/
Expected a `Response`, `HttpResponse` or `StreamingHttpResponse` to be returned from the view, but received a `<class 'NoneType'>`

问题根源

  • 视图函数缩进错误:views.py中post方法的if serializer.is_valid():语句后,后续代码未缩进,导致当序列化器验证失败(比如凭证错误触发ValidationError)时,代码仍会继续执行,最终函数走到末尾未返回任何响应,返回None触发断言错误。
  • 未处理序列化器验证失败的场景:当序列化器验证不通过时,视图没有返回对应的错误响应。

修复方案

1. 修正views.py的post方法缩进并处理验证失败场景

from rest_framework import status

def post(self, request):
    serializer = LoginSerializer(data=request.data)
    if serializer.is_valid():
        email = serializer.validated_data['email']
        password = serializer.validated_data['password']

        user = authenticate(email=email, password=password)

        if user:
            login(request, user)
            return redirect('/')
        else:
            return Response({'erro': 'user nao encontrado'})
    # 处理序列化器验证失败的情况
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

2. 优化LoginSerializer的validate方法

确保所有分支逻辑完整,避免出现未定义变量:

class LoginSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(required=True)
    password = serializers.CharField(write_only=True, style={'input_type': 'password'})

    class Meta:
        model = Profile
        fields = ['email', 'password']

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')

        # 先检查邮箱和密码是否都提供
        if not email or not password:
            raise serializers.ValidationError('邮箱和密码不能为空')

        user = authenticate(email=email, password=password)
        if not user:
            raise serializers.ValidationError('O usuário não existe')

        attrs['user'] = user
        return attrs

说明

  • 修正缩进后,只有当序列化器验证通过时才会执行后续的用户认证逻辑;验证失败时直接返回序列化器的错误信息。
  • 优化后的序列化器先检查邮箱和密码是否存在,避免后续出现user未定义的问题,同时确保验证逻辑更严谨。

内容的提问来源于stack exchange,提问作者user19979272

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:52:53