我使用formset工厂生成一组动态表单元素。我想添加一组动态单选按钮和下拉菜单,但是当我使用ChoiceField时,search.is_valid()的计算结果为false。我确定我做了一些明显错误的事,但我无法找到它。
...
search_formset = formset_factory(SearchForm, extra=num_extra_charts)
# data to initialize forms
data = {
'form-TOTAL_FORMS': str(num_extra_charts),
'form-INITIAL_FORMS': str(num_extra_charts),
'form-MAX_NUM_FORMS': '',
}
self.search_forms = search_formset(get_request or data)
if self.search_forms.is_valid():
...
class SearchForm(forms.Form):
ORDERS = [('ASC', 'ASC'),
('DESC', 'DESC')]
search = forms.CharField(label='',
max_length=250,
required=False,
widget=forms.TextInput(
attrs={'placeholder': 'ex. Matt Damon AND war'}),
)
property = forms.CharField(label='',
max_length=250,
required=False,
widget=forms.TextInput(
attrs={'placeholder': 'Property Filter'}),
)
limit = forms.CharField(label='',
max_length=250,
required=False,
widget=forms.TextInput(
attrs={'placeholder': 'Limit - Default: 25'}),
)
orders = forms.CharField(widget=forms.Select(choices=ORDERS))
答案 0 :(得分:1)
你有:
self.search_forms = search_formset(get_request or data)
这很不寻常。这意味着formset始终是绑定的。
通常你会有
self.search_forms = search_formset(get_request or None)
由于您没有required=False
,这意味着您必须在表单数据中提供orders
字段的值,否则您将收到错误。