【发布时间】:2016-11-28 23:26:20
【问题描述】:
我有一个表单,它利用了我创建了一个表单集的选择参数。当呈现包含表单集的页面时,使用选项参数的字段显示下拉选择小部件。用户填写的表格没有错误。但是,用户未填写的表单对于所有其他字段都有“此字段是必需的”错误,但使用选择小部件的字段除外。
似乎选择字段的初始值导致表单被视为半填表单,因此表单验证过程会为未填写的必填字段引发错误。
# Form:
class OwnerForm(forms.Form):
name = forms.CharField(label = 'Name', max_length = 20)
owner_entity = forms.ChoiceField(label = 'Owner Entity', choices = OWNER_ENTITIES)
num_of_shares = forms.DecimalField(label = 'Number of Shares' , min_value = 0.0, max_digits = 5, decimal_places = 2)
share_class = forms.ChoiceField(label = 'Share Class', choices = SHARE_CLASSES)
joined_date = forms.DateField(label = 'Joined Date', help_text = 'mm/dd/yyyy')
# View:
# In Get method:
OwnersFormSet = formset_factory(OwnerForm, extra = 5)
...
# In Post method:
the_owners_forms = OwnerFormSet(request.POST)
if not the_owners_forms.is_valid():
the_owners_forms_errors = the_owners_forms.errors
那么,问题是我该如何处理这种行为,以使未填充的表单不会因为 select 方法的初始值而被视为 hal 填充的表单?
【问题讨论】:
-
我在发布问题之前确实尝试过,但没有奏效。我在 OWNER_ENTITIES 中添加了一个 (None, '------------'),但它跳过了这个并选择了元组中的下一个元素。我的想法是在收到表单时手动删除这些初始值并在手动修改后运行 is_valid。
-
如果你想使用 javascript,我有一个更优雅的解决方案来解决你的问题
-
非常欢迎您的解决方案!我也想知道如何使用 Django 解决这个问题。
标签: django forms django-forms django-views