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

时间:2014-05-03 00:54:48

标签: python django django-rest-framework

发布以下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",)

该视图只是我拥有的ModelViewSet模型的基本User

也许我错误地配置了url.py文件?这就是我对urlpatterns所拥有的。

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

1 个答案:

答案 0 :(得分: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")
...