Jon Martin
Jon Martin

Reputation: 3392

Pass arbitrary number of form elements to Django view

I currently have a form template that allows the user to add or remove form elements as they see fit (mostly cloning a set of fields). I do the cloning and removing via JQuery, but I'm stuck on how to pass these form elements into a Django view. The normal way would be to create a Django form class and then read the fields from request.POST, but I don't know how to deal with an arbitrary number of elements. What's the best way to do this?

Upvotes: 0

Views: 117

Answers (1)

Aylen
Aylen

Reputation: 3554

If these forms correspond to the same type of object, you should be using Formsets (if you are using ModelForm take a look at Model formsets). In particular you might want to read about how to save the formset data.

This answer explains how to properly change attributes in forms added with jQuery, to avoid repeating fields' IDs that would conflict when submitting the formset. In that thread there are also many plugins/snippets to do this, in case you want to take a look at them.

Upvotes: 1

Related Questions