Django find which form was submitted

I have 3 sets of forms in one template. Only one will be displayed at a given time (the other two are completely hidden):

<form style="display: none;">

All 3 forms are displayed with default values ​​and must be valid even if data has not been entered.

However, I would like to know which one was sent when I check view.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 do not want f2 or f3 to be saved if only f1 was submitted (each set of forms has its own submit button). The "# Do many of calculate ..." part is quite extensive, and I don’t want to copy the code again unnecessarily.

How can I use the same view, but save and perform calculations only for the presented set of forms?

+4
2

:

<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>

request.POST :

'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
+6

, , , . .

, :

<form yourcode>
    # ... ...
    # your input fields
    # ... ... 
    <input method="post" type="submit" name="action" class="yourclass" value="Button1" />
</form>

<form yourcode>
    # ... ...
    # your input fields
    # ... ... 
    <input method="post" type="submit" name="action" class="yourclass" value="Button2" />
</form>

, - Button1, - Button2

:

def yourview():
    # ... ... 
    # Your code
    # ... ... 
    if request.method == 'POST':
        if request.POST['action'] == "Button1":
            # This is the first form being submited
            # Do whatever you need with first form

        if request.POST['action'] == "Button2":
            # This is the second form being submited
            # Do whatever you need with second form

, , . , .

0

All Articles