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

Django LoginSerializer出现KeyError: 'password'问题求助

解决Django REST Framework登录API的KeyError问题

问题根源

你的LoginSerializer在fields中声明了password字段,但validate方法返回的字典里并未包含password。DRF在序列化生成响应数据时,会尝试从validated_data(即validate方法返回的字典)中获取所有fields里声明的字段,找不到password就会抛出KeyError。

解决方法

最合理的方案是将password字段设置为仅写入(write-only),因为登录接口只需要接收密码,不需要返回密码(返回密码存在安全风险)。

修改序列化器中的password字段定义,添加write_only=True参数:

class LoginSerializer(serializers.ModelSerializer):
    email = serializers.EmailField()
    # 添加write_only=True,标记字段仅用于输入
    password = serializers.CharField(min_length=6, write_only=True)
    username = serializers.CharField(read_only=True)
    tokens = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ["email", "password", "username", "tokens"]

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

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

        if not user:
            raise AuthenticationFailed("Invalid credentials")
        if not user.is_active:
            raise AuthenticationFailed("Account is not active, please contact admin")

        return {
            "email": user.email,
            "username": user.username,
            "tokens": user.tokens(),
        }

原理说明

write_only=True会告诉DRF:该字段仅用于接收客户端传入的数据(反序列化阶段),在生成响应数据(序列化阶段)时会忽略这个字段,不会尝试从validated_data中获取它的值,从而避免KeyError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:41:04