From what I understand from the documentation they formsets
allow you to work with multiple forms on the same page.
For example, in this code snippet 4 forms are being created based on the models Invoice
e Item
,
ItemFormSet = inlineformset_factory(
Invoice,
Item,
form=ItemForm,
fields=('description', 'quantity', 'rate', 'amount'),
extra=4
)
However, if I want to create content dynamically, for example in my case adding more items to an invoice, is it possible to use formsets
?
If possible, I would appreciate if you give me a small example.
If possible. So far the best way I've found to do this is using JavaScript/jQuery, I haven't found a way to do this dynamically using just Django.
I imagine that in your template, you are doing something like this:
This should be showing you four forms for each
Item
of yourInvoice
. Now what we need is a couple of buttons to dynamically add or remove forms, see how I'm using a<table></table>
:The function I've always used to add forms dynamically is the one recommended in Paolo Bergantino 's answer . Let's see how to create the functionality of the buttons in JavaScript:
It may seem a bit complicated at first, but in general what is being done is updating the quantities of the forms, since he
ManagementForm
keeps track of the total forms. In the same way, it is necessary to update the form elements counter, as I mentioned in the JavaScript, the form elements are enumerated:So if you add a fifth form it should respect that order and be as follows:
Final note:
I am assuming that the prefix of your form is
'item'
, if this is not the case you can force it to be so in your definitionformset
: