2015-04-07 56 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 

因此,您可以使用按鈕的值控制提交哪個表單。還有其他方法可以做到這一點,但這種方式對我的問題更容易。

您也可以使用屬性過濾的形式