问题描述
是否可以提交两种不同的表单,在django中提交一个提交按钮?
我有一个形式称为仪器和4个相等的形式配置。现在我想提交一个配置和工具。例如仪器+配置1和仪器+配置2.每个配置都有自己的提交按钮。
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" >
并调用js函数'onclick':
and call a js function 'onclick':
submitForms = function(){
console.log('ok'); //only for testing
document.forms["firstForm"].submit();
document.forms["secondForm"].submit();
}
这是我在views.py中的方法:
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
推荐答案
而不是在HTML中使用多个< form ..>
标签,只能使用一个 ;表单>
标签,并添加其下所有表单的字段。
Instead of having multiple <form ..>
tags in html, use only one <form>
tag and add fields of all forms under it.
模板示例
<form >
{{ form1.as_p }}
{{ form2.as_p }}
{{ form3.as_p }}
</form>
所以当用户提交表单时,您将获得所有表单数据,那么您可以做什么正在考虑。作为
So when user submits the form you will get all forms data in view, then you can do what you are doing in view. As
if request.method == 'POST':
form1 = Form1(request.POST)
form2 = Form2(request.POST)
print(request.POST)
if form1.is_valid() or form2.is_valid():
最好使用在这种情况下。
Its better to use form prefix
in such cases.
所以你可以做
if request.method == 'POST':
form1 = Form1( request.POST,prefix="form1")
form2 = Form2( request.POST,prefix="form2")
print(request.POST)
if form1.is_valid() or form2.is_valid():
else:
form1 = Form1(prefix="form1")
form2 = Form2(prefix="form2")
这篇关于django提交两个不同的表单与一个提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!