2015-04-07 57 views
4

我在一个模板中有3个formset。只有一个会在给定时间(另外两个是完全隐藏)可见:Django找到哪个表单提交了

<form style="display: none;"> 

所有3种形式呈现使用默认值,应该是有效的,即使没有输入数据。

但是,我想知道在验证views.py时提交了哪一个。

在views.py我有以下几点:

def submitted(request): 

    f1 = formset1(request.POST) 
    f2 = formset2(request.POST) 
    f3 = formset3(request.POST) 

    if f1.is_valid() or f2.is_valid() or f3.is_valid(): 
     f1.save() 
     f2.save() 
     f3.save() 
     # Do a lot of calculations... 

     return render(request, 'submitted.html') 

的问题是,我不希望如果只有F1提交F2或F3保存(每个表单集都有自己的提交按钮)。 '#做很多计算......'部分非常广泛,我不想不必要地复制代码。

如何使用相同的视图,但仅保存并仅对提交的表单集进行计算?

+0

两者的提交按钮被点击将在'request.POST'的ID。 – Ben

+0

感谢您的快速响应!我不确定你的意思 - 对不起!我试着在submitted.html中查看f1.id并没有看到任何东西? – wernerfeuer

+0

看我的回答:) – Ben

回答

6

如果每种形式都有它自己的提交按钮:

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

然后提交按钮的名称将在request.POST无论哪个形式提交:

'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 
+0

谢谢@Ben!太棒了! – wernerfeuer

0

我也遇到了类似的问题我在一个模板中有几个表单,我需要知道哪一个表单已提交。为此,我使用了提交按钮。

比方说,你有形式是这样的:

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

你可以阅读的差异之间的提交按钮,第一个值是Button1的,第二个是Button2的

在你看来,你可以有这样的控制:

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 

因此,您可以使用按钮的值控制提交哪个表单。还有其他方法可以做到这一点,但这种方式对我的问题更容易。

您也可以使用属性过滤的形式