0

I have to handle two forms in one function:

HTML page

<form name="selectgenderform" method = "POST">
  <select name='gender'>
   <option>Male</option>
   <option>Female</option>  
  </select>
 <input type = 'submit' name ='searchbtn' value= 'search' >
</form>


<form name="selectionform" method = "POST">
  <input type = 'hidden' name = 'valueofnumber' >
 <input type = 'submit' name = 'searchbtn' value= 'search' >
</form>

Views.py

 def formselection(request):
   if selectgenderform in request.POST:
     gender = request.POST.get('gender')
     ...

   elif selectionform in request.POST:
     value = request.POST.get('valueofnumber') 

My query is to handle multiple forms in one function but this will not according to my demand

2 Answers 2

1

if you want to keep the two separate forms:

if request.method == "POST" and "selectgenderform" in request.POST:
    *something*

if request.method == "POST" and "selectionform" in request.POST:
    *something*

you might also have to change the submit input names to "selectgenderform" and "selectionform"

Sign up to request clarification or add additional context in comments.

Comments

1

You can pass multiple forms and handle it using single function. However the trick is to keep the forms under one form tag in template. (Bear with me as I am typing on my phone)

views.py

def yourView(request):
    form1 = form1()
    form2 = form2()

    if request.method == "post":
        form1 = form1(request.POST)
        form2 = form2(request.POST)

        if form1.is_valid():
            #do something
        if form2.is_valid():
            #do something else 
   contest = { "form1": form1, "form2": form2 }
   return render(request, 'template.html', context=context)

template.html

    <form method="POST">
        {%csrf_token%}
        {{form1.as_p}}
        {{form2.as_p}}
    <button type="submit"> Submit </button>
    </form>

3 Comments

Thank you for your answer, but with this one first I have to make forms of table from models.py ?
@Mahad_Akbar Not necessary. You can handle it manually too, but this one using forms is little bit cleaner approach.
Kindly can you explain it with manually, I am try it for long but this was not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.