我注意到嵌套在另一个表单中的 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 中省略了前 2 行,则该列表不会因在浏览器中的修改而受到影响。
一个很好的解释为什么会发生这种情况,或者修改我的代码将不胜感激