I noticed weird behaviour of FormSet which is nested inside another form.
Sample app:
#### 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')
Class-based view for displaying forms:
#### 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)
An the template used for displaying 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>
If I omit first 2 lines in form_valid the list is untouched by its modification in a browser.
A nice explanation why is this happening, or maybe amend of my code would be more than appreciated