Skip to main content
 首页 » 编程设计

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

2025年05月04日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",) 

View 只是我拥有的User 模型的基本ModelViewSet

可能是我配置的url.py文件有误?这就是我的 urlpatterns。

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

请您参考如下方法:

看来您可能遗漏了一些代码。我有同样的问题导致验证器函数不返回 attrs 变量所以我的代码看起来像这样:

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

这解决了它:

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

附带说明,您忘记提出一个异常(exception):

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

将其更改为:

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