I have 3 formsets in a single template. Only one would be visible at a given time (the other two are hidden entirely):
<form style="display: none;">
All 3 forms are rendered with default values and should be valid even if no data was entered.
However, I would like to know which one was submitted when I validate the views.py.
In views.py I have the following:
def submitted(request):
f1 = formset1(request.POST)
f2 = formset2(request.POST)
f3 = formset3(request.POST)
if f1.is_valid() or f2.is_valid() or f3.is_valid():
f1.save()
f2.save()
f3.save()
# Do a lot of calculations...
return render(request, 'submitted.html')
The problem is that I don't want f2 or f3 saved if only f1 was submitted (each formset has their own submit button). The '# Do a lot of calculations...' part is quite extensive and I don't want to replicate the code unnecessarily.
How can I use the same view, but only save and do the calculations for only the submitted formset?
If each form has it's own submit button:
<form id='form1'>
...
<input type='submit' name='submit-form1' value='Form 1' />
</form>
<form id='form2'>
...
<input type='submit' name='submit-form2' value='Form 2' />
</form>
<form id='form3'>
...
<input type='submit' name='submit-form3' value='Form 3' />
</form>
Then the name of the submit button will be in request.POST
for whichever form was submitted:
'submit-form1' in request.POST # True if Form 1 was submitted
'submit-form2' in request.POST # True if Form 2 was submitted
'submit-form3' in request.POST # True if Form 3 was submitted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With