0

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

vucalur
  • 6,007
  • 3
  • 29
  • 46

1 Answers1

0

I'm not sure why you think it would do anything else. Nesting formsets - or other forms - inside forms is not supported, and there is nothing in the documentation to imply it is. Django would have to specifically include code to instantiate the formset with data from the post in that situation, and it doesn't.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Since nesting is not supported, is there some more elegant solution for combining regular fields with a list of fields in a single Form ? – vucalur Jun 30 '13 at 06:34