1

如何使 django formset 中的所有表单都需要?我正在使用RequiredFormSet. 但它不起作用。我错过了什么吗?谢谢

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)

更新:这里追溯,这是我的观点

4

1 回答 1

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
于 2012-04-30T19:47:54.720 回答