我注意到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中省略前两行,则列表在浏览器中的修改不受影响 一个很好的解释为什么会发生这种情况,或者修改我的代码将会非常感激
答案 0 :(得分:0)
我不确定你为什么认为它会做任何其他事情。不支持在表单内嵌套表单集或其他表单,并且文档中没有任何内容暗示它是什么。 Django必须专门包含代码,以便在该情况下使用帖子中的数据实例化formset,但事实并非如此。