python - 我如何使表单集成为必需的

标签 python django django-forms

如何使 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)

更新:这里traceback这是 my view

最佳答案

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

这不会引发KeyError

更新。

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

关于python - 我如何使表单集成为必需的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10389081/

相关文章:

python - mongoengine 引用字段查询

python - 密码未使用 Django 以及一些缺失的列进行哈希处理

python - 尝试构造时,子节点被视为孙子节点

python - 有很多选择的 Django 选择字段 - 是否有一个简单有效的解决方案?

python - 使用更改django模板中表单字段的名称属性

python - Django一对多表单

python - 使用 python 中的装饰器发送请求正文

python - 窗体的干净方法没有被调用

python - 围绕 matplotlib 线绘制边框

python - Django 将模型实例传递给略有不同的模型