2012-04-30 52 views
1

如何使所有形式在django formset中都是必需的?我正在使用RequiredFormSet。但它不起作用。我錯過了什麼嗎?感謝我該如何使formset需要

class RequiredFormSet(BaseFormSet): 
    def __init__(self, *args, **kwargs): 
     super(RequiredFormSet, self).__init__(*args, **kwargs) 
     for form in self.forms: 
      form.empty_permitted = False 
     #self.forms[0].empty_permitted = False 

class RecipeIngredientForm(CustomModelForm): 
    class Meta: 
     model = RecipeIngredient 
    def clean(self): 
     ingredient = self.cleaned_data['ingredient'] 
     unit = self.cleaned_data['unit'] 
     if ingredient.ing_type in (ingredient.TYPE_WET, ingredient.TYPE_DRY) and not unit: 
      raise forms.ValidationError('unit missing for %s.' % ingredient.name) 
     return self.cleaned_data 
RecipeIngredientFormSet = formset_factory(RecipeIngredientForm, formset=RequiredFormSet) 

更新:這裏traceback這裏是my view

+0

「不起作用」對您的問題沒有特別有用的描述。是否有錯誤/追溯? –

回答

1
ingredient = self.cleaned_data.get('ingredient') 
unit = self.cleaned_data.get('unit') 

這不會提高KeyError

UPD。

def clean(self): 
    ingredient = self.cleaned_data.get('ingredient') 
    unit = self.cleaned_data.get('unit') 
    if ingredient is not None and ingredient.ing_type in (ingredient.TYPE_WET, ingredient.TYPE_DRY) and not unit: 
     raise forms.ValidationError('unit missing for %s.' % ingredient.name) 
    return self.cleaned_data 
+0

謝謝。但是現在我得到''NoneType'對象沒有屬性'ing_type'' – Kulbir

+0

你應該在這個'if ingredient.ing_type:...' – San4ez

+0

之前檢查'成分類型'(如果它是None)得到同樣的錯誤:( – Kulbir

相關問題