2013-03-11 42 views
3

我的問題是關聯到這個鏈接:How to allow user to input comma如何在通過表單驗證之前獲取表單字段值?

所以我試圖做所有的可能性,只是爲了使它的工作。現在我試圖在通過form.is_valid()進行驗證之前執行保存操作時獲取值傳遞。

我順利拿到由這樣的值:

.........  
if request.method == 'POST': 
    if request.POST['process'] == 'addtrans': 
     tform = AddTransactionForm(request.user, 
            request.POST) 

     print tform.fields['amount'] // this is the value that I want to get 

     if tform.is_valid(): 
.......... 

但不幸的輸出是這樣的:

<django.forms.fields.DecimalField object at 0x7fcc84fd2c50> 

如何獲得準確值或解碼該輸出?我希望有人試過這個。

+0

您將通過'request.POST.get('amount')'獲得原始輸入。 'tform.fields'將爲這些值提供適當的對象。 – Rohan 2013-03-11 06:15:25

+0

是的,我已經這樣做,我得到的金額。我只想得到確切的參數,因爲我想用它來替換當前值通過POST – catherine 2013-03-11 06:18:42

+0

@Rohan你知道用其他方式替換POST傳遞的值嗎? – catherine 2013-03-11 06:20:43

回答

3

我覺得這是你描述 -

def transaction(request): 
    if request.POST.method == 'POST': 
     post = request.POST.copy() 
     if 'amount' in post: 
      post['amount'] = post['amount'].replace(',','') 
     tform = AddTransactionForm(request.user, post) 
     #... 

(你必須創建request.POST字典的副本,因爲它是不可變的)。

+0

哇,它的工作。最後一個問題,這是安全的嗎? – catherine 2013-03-11 07:30:25

+0

是的。真高興你做到了。 – 2013-03-11 07:38:10