'django submit two different forms with one submit button
is it possible to submit two different forms, with one submit button in django? i have one form called "instrument" and 4 equal forms "config". now i'd like to submit always one config and instrument. e.g. instrument + config 1, and instrument + config 2. and every config have its own submit button.
i have tried it with one button in the config form:
<input onclick="submitForms()" class="btn btn-primary cfg" type="submit" value="Start" >
and call a js function 'onclick':
submitForms = function(){
console.log('ok'); //only for testing
document.forms["firstForm"].submit();
document.forms["secondForm"].submit();
}
this is my method in the views.py:
if request.method == 'POST':
form1 = dataproviderInstrumentForm(request.POST)
form2 = dynamicTimeseriesForm(request.POST)
print(request.POST)
if form1.is_valid() or form2.is_valid():
# do some stuff
else:
form1 = dataproviderInstrumentForm() # an unbound form
form2 = dynamicTimeseriesForm() # an unbound form
Solution 1:[1]
Extending the @Rohan answer and adding more control on forms.
Not dependent forms/Without relationship/Save any form from multiple forms
Check individually each form to check which form are not valid. Then store them into context if contain errors or redirect them.
if request.method == 'POST':
form1 = Form1( request.POST,prefix="form1")
form2 = Form2( request.POST,prefix="form2")
if form1.is_valid():
# save them
# context['form1_message'] = 'Form1 saved'
else:
#save them into context
context['form1']= form1
if form2.is_valid():
# save them
# context['form2_message'] = 'Form2 saved'
else:
#save them into context
context['form2']= form2
if form1.is_valid() and form2.is_valid():
#that's mean both form is valid and saved successfully
return redirect('page')
else:
return render('/page', context)
else:
form1 = Form1(prefix="form1")
form2 = Form2(prefix="form2")
Dependent forms/Modelform(1-1,1-m)/Relationship form
One Parent form and one child form that depends on Parent form. if both forms are saved or checked errors at same time then we will use this method.
if request.method == 'POST':
form1 = Form1( request.POST,prefix="form1")
form2 = Form2( request.POST,prefix="form2")
if not form1.is_valid():
#save them into context
context['form1']= form1
if not form2.is_valid():
#save them into context
context['form2']= form2
if form1.is_valid() and form2.is_valid():
#that's mean both form is valid and saved successfully
return redirect('page')
else:
return render('/page', context)
else:
form1 = Form1(prefix="form1")
form2 = Form2(prefix="form2")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
