Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django find which form was submitted

Tags:

django

formset

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?

like image 534
wernerfeuer Avatar asked Apr 07 '15 08:04

wernerfeuer


1 Answers

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
like image 173
Ben Avatar answered Sep 27 '22 19:09

Ben