Django find which form was submitted Django find which form was submitted django django

Django find which form was submitted


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


I have faced a similar issue where I had several forms in a template and I need to know which one was submitted. To do this I used the submit button.

Let's say you have the forms like this:

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

You can read the difference between those submit buttons, the value of the first is Button1 and the second is Button2

In your view you can have a control like this:

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

So, you can control which form is submitted using the value of the button. There is other ways to do that, but this way was the easier for my issue.

You can also use the name property to filter the forms