0
我正在使用formset工廠生成一組動態表單元素。我想添加一組動態單選按鈕和下拉菜單,但是當我使用ChoiceField時,search.is_valid()的計算結果爲false。我敢肯定,我正在做一些明顯錯誤的事情,但我找不到它。Django formset factory ChoiceField導致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))
是的,我意識到發佈後大約5分鐘。但是,據我所知,formset必須具有數據的初始值,否則會出現管理錯誤。 – Optimus
如果formset是* bound *,則只需要管理表單值。如果表單未綁定(例如'self.search_formset(None)'或'self.search_formset()'),那麼您將不會收到管理錯誤。查看關於[綁定和未綁定表單]的文檔(https://docs.djangoproject.com/en/1.9/topics/forms/#bound-and-unbound-form-instances)。 – Alasdair
關鍵是我在我的html模板中意識到我需要'{{management_form}}'之前添加了該數據變量。然後,我從未刪除它,因爲一切正常。謝謝,現在這樣更清晰/更容易理解。 – Optimus