Django formset factory ChoiceField 导致 is_valid 失败和 return false
Django formset factory ChoiceField causes is_valid to fail and return false
我正在使用表单集工厂生成一组动态的表单元素。我想添加一组动态单选按钮和下拉菜单,但是当我使用 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))
你有:
self.search_forms = search_formset(get_request or data)
这很不寻常。这意味着表单集总是绑定的。
通常你会
self.search_forms = search_formset(get_request or None)
由于您没有 required=False
,这意味着您必须在表单数据中提供 orders
字段的值,否则您将收到错误消息。
我正在使用表单集工厂生成一组动态的表单元素。我想添加一组动态单选按钮和下拉菜单,但是当我使用 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))
你有:
self.search_forms = search_formset(get_request or data)
这很不寻常。这意味着表单集总是绑定的。
通常你会
self.search_forms = search_formset(get_request or None)
由于您没有 required=False
,这意味着您必须在表单数据中提供 orders
字段的值,否则您将收到错误消息。