0
我注意到嵌套在另一個表單中的FormSet的奇怪行爲。
示例應用程序:用於顯示形式內部FormSet需要手動刷新請求
#### forms: ####
class BookForm(forms.Form):
title = forms.CharField()
BookFormSet = formset_factory(BookForm, extra=3)
class PublisherForm(forms.Form):
name = forms.CharField()
books = BookFormSet(prefix='books')
基於類的視圖:
#### views: ####
class PublisherCreateView(FormView):
template_name = 'library/create.html'
form_class = PublisherForm
def form_valid(self, publisherForm):
# workaround: somehow publisherForm's inner list need to be restored from POST request:
# otherwise it'll be empty FormSet as if it was constructed using BookFormSet(prefix='books')
books = BookFormSet(self.request.POST, self.request.FILES, prefix='books')
publisherForm.books = books
do_sth_fancy_dancy_with(publisherForm)
return super(PublisherCreateView, self).form_valid(publisherForm)
一種用於顯示PublisherForm模板:
#### template: ####
<form action="." method="post">{% csrf_token %}
<div class="section">
{{ form.as_p }}
</div>
<h2>Books</h2>
<div class="books">
{{ form.books.as_p }}
<p><input type="button" id="add-row" value="Add another book"/></p>
</div>
<input type="submit" value="Save"/>
</form>
如果我省略前兩行中form_valid該列表未經瀏覽器修改。
一個很好的解釋爲什麼會發生這種情況,或者可能我的代碼的修改將不勝感激
由於不支持嵌套,是否有一些更優雅的解決方案將常規字段與單個表單中的字段列表組合? – vucalur