尝试更新模型对象时,“NoneType”类型的参数不可迭代

时间:2013-05-14 16:43:16

标签: django

获取错误Argument of type 'NoneType' is not iterable并且无法找出原因。

它发生在第if model_form.is_valid():

Views.py

def update_model(request, pricemodel_id):
    """ Update a part given its id. """
    pricemod = Part.objects.get(id=pricemodel_id)
    if request.method == "POST":
        print "post request"
        model_form = priceform(request.POST, request.FILES, instance=pricemod)
        model_form.is_update = True
        if request.user == pricemod.adder:
            #from ipdb import set_trace; set_trace()
            if model_form.is_valid():

Forms.py

class priceform(ModelForm):
# price Form: form associated to the Part model
    def __init__(self, *args, **kwargs):
        super(priceform, self).__init__(*args,**kwargs)
        self.is_update=False
        choices = UniPart.objects.all().values('manufacturer').distinct()
    def clean(self):
        if self.cleaned_data and 'modelname' not in self.cleaned_data:
            raise forms.ValidationError("Some error message")
            if not self.is_update:
                return self.cleaned_data
            return self.cleaned_data
    class Meta:
        model = Part

1 个答案:

答案 0 :(得分:3)

看起来这是因为你的干净方法中的错误缩进。当前它不返回任何内容,即它返回None,但必须返回self.cleaned_data。您的所有clean方法代码都在if下,这会引发异常。如果此if不匹配,则返回None。

试试这个:

class priceform(ModelForm):
    # ...
    def clean(self):
        if self.cleaned_data and 'modelname' not in self.cleaned_data:
            raise forms.ValidationError("Some error message")
        if not self.is_update:
            return self.cleaned_data
        return self.cleaned_data

    # ...