django 用一个提交按钮提交两种不同的表单 [英] django submit two different forms with one submit button
问题描述
是否可以在 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 中使用多个 标签,只使用一个
标记并在其下添加所有表单的字段.
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 用一个提交按钮提交两种不同的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!