2013-05-14 87 views
2

獲取錯誤Argument of type 'NoneType' is not iterable並找不到原因。嘗試更新模型對象時無法迭代「NoneType」類型的參數

它發生在該行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 

回答

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 

    # ... 
+0

謝謝你能真正簡單介紹一下什麼是乾淨的方法做以及如何做的is_valid方法知道檢查一下嗎? – user1328021 2013-05-14 17:21:48

+0

'is_valid'調用方法鏈,執行驗證。最後一部分:每個字段調用'clean_ '方法,然後調用'clean'方法。 'clean_ '方法驗證專用於''字段的數據。在'clean'中,'self.cleaned_data'包含已經由相應的'clean_ '方法驗證的數據。因此,這裏可以驗證一些通用規則,以及與兩個或多個鏈接字段相關的規則,例如,一個領域必須考慮到另一個領域。這裏是[詳細文檔](https://docs.djangoproject.com/en/dev/ref/forms/validation/) – stalk 2013-05-14 21:19:34

相關問題