Python类型'NoneType'的参数不可迭代

2 投票
1 回答
1382 浏览
提问于 2025-04-18 05:12

我在发送下面这个json数据时遇到了错误:{"email":"test@test.com", "password":"12345", "repeatPassword":"12345"}

我在使用Django-Rest_framework,所以我觉得可能是我设置的地方有问题?

这是我用的序列化器

class UserSerializer(serializers.ModelSerializer):
    repeatPassword = serializers.CharField(write_only=True, required=True, label="Re-enter Password")
    def validate(self, attrs):
        passwordValue = attrs["password"]
        repeatPasswordValue = attrs["repeatPassword"]


        if passwordValue is not None and passwordValue != "":
            if repeatPasswordValue is None or repeatPasswordValue == "":
                raise serializers.ValidationError("Please re-enter your password")

        if passwordValue != repeatPasswordValue:
            serializers.ValidationError("Passwords must match")

        return attrs

    class Meta:
        model = User
        fields = ("email", "username", "password")
        read_only_fields = ("username",)
        write_only_fields = ("password",)

这个视图只是我为User模型创建的一个基本的ModelViewSet

也许我在url.py文件的配置上有错误?这是我在urlpatterns中的设置。

urlpatterns = patterns('',
    (r'^user/$', UserViewSet.as_view({"get": "list", "put": "create"})))

1 个回答

1

看起来你可能漏掉了一些代码。我之前也遇到过同样的问题,是因为一个验证函数没有返回 attrs 变量,所以我的代码看起来是这样的:

def validate_province(self, attrs, source):
    // unimportant details

这样做就解决了这个问题:

...
    def validate_province(self, attrs, source):
        // unimportant details
        return attrs
...

顺便提一下,你忘记抛出一个异常了:

...
    if passwordValue != repeatPasswordValue:
        serializers.ValidationError("Passwords must match")
...

把它改成:

...
    if passwordValue != repeatPasswordValue:
        raise serializers.ValidationError("Passwords must match")
...

撰写回答