2014-02-12 48 views
0

我是全新的Django,我想第一次使用Django的形式。我已經找到了這個,但我仍然沒有找到答案。基本上,我有這樣一個觀點:添加一個新的字段Django的形式

def pay(request):  
if request.method == 'POST': 
    form = PaymentForm(request.POST) 
    if form.is_valid(): 
     # I have to calculate the checksum here 
     myModel = form.save() 
    else: 
     print form.errors 
else: # The request is GET 
    form = PaymentForm() 
return render_to_response('payment/payment.html', {'form':form}) 

,我希望有一個附加字段,添加檢查和到從我從那麼當用戶提交校驗應加入並添加到項目的形式得到了輸入的形式表單和表單應發送到外部服務器。但我不知道該怎麼做(我在模型中定義了校驗和)。任何人都可以幫助我嗎?

我的模型看起來是這樣的:

class PaymentModel(models.Model): 
alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed!') 
secret_key = '6cd118b1432bf22942d93d784cd17084' 
pid = models.CharField(primary_key=True, max_length=50, validators=[alphanumeric]) 
sid = models.CharField(primary_key=True, max_length=50, validators=[alphanumeric]) 
amount = models.DecimalField(max_digits=9, decimal_places=2) 
success_url = 'http://localhost:8000/success' 
cancel_url = 'http://localhost:8000/cancel' 
error_url = 'http://localhost:8000/error' 
checksum = 0 

def calc_checksum(self): 
    checksumstr = "pid=%s&sid=%s&amount=%s&token=%s"% (self.pid, self.sid, self.amount, self.secret_key) 
    m = md5(checksumstr) 
    checksum = m.hexdigest() 
    return checksum 

def __unicode__(self): #returns the unicode representation of the object 
    return self.name 

和我的形式如下:

class PaymentForm(ModelForm): 
    class Meta: 
     model = PaymentModel 
+0

您需要將此字段添加到「PaymentForm」... – Silwest

+0

您可以更新您的問題並將其添加到表單結構中,而不是將其作爲註釋發送。因爲您使用了'ModelForm',所以您最好發佈'PaymentModel' – FallenAngel

+0

我按照您的建議編輯了該主題:) –

回答

0

可以使用commit=False關鍵字參數form.save()

def pay(request):  
    if request.method == 'POST': 
     form = PaymentForm(request.POST) 
     if form.is_valid(): 
      # Will not save it to the database 
      myModel = form.save(commit=False) 

      # keep your business logic out of the view and put it on the form or model 
      # so it can be reused 
      myModel.checksum = form.calculate_checksum() 
      myModel.save() 
     else: 
      print form.errors 
    else: # The request is GET 
     form = PaymentForm() 

    return render_to_response('payment/payment.html', {'form':form}) 

Django form.save() documentation.

+0

不幸的是它仍然無法工作。我添加了模型和表單。有可能看到爲什麼? –

+0

我不清楚你的問題是什麼。你想在數據庫中存儲'checksum'嗎? –

+0

不,我想打包校驗和以及其他數據(pid,sid,金額等),並將它們全部發送到需要這些字段的外部服務器。 –

相關問題