2015-05-07 29 views
0

我有一個簡單的創建視圖爲一個簡單的模型與默認值字段。我想通過僅提供沒有默認值的字段來測試此設置。 測試失敗,因爲在數據庫中沒有創建對象。玩過打印後,我知道以下幾點: 模型clean()通過,並且提供了默認值。 響應聲明「此字段是必需的。」爲maxVar和minVotes。 (和發送這兩個值可以通過測試。)Django的CreateView - 忽略POST測試的默認值

的失敗的測試是:

from django.test import TestCase 
from django.utils import timezone 
from django.core.urlresolvers import reverse 
import datetime 

from testcase.models import Poll 

class PollCreateTest(TestCase): 
    def test_create_with_description_only(self): 
     """description should be sufficient to create a poll.""" 
     self.assertEqual(Poll.objects.count(), 0) 
     x = self.client.post(reverse('rating:create'), {'description':'A Poll'}) 
     #print x 
     self.assertEqual(Poll.objects.count(), 1) 

與對應models.py:

from django.db import models 
from django.core.urlresolvers import reverse 

class Poll(models.Model): 
    description = models.TextField() 
    pub_date = models.DateTimeField('date published') 
    minVotes = models.IntegerField(default=5) 
    maxVar = models.FloatField(default = 0.0) 
    finished = models.BooleanField(default=False) 

而views.py:

from django.shortcuts import render 
from django.views import generic 

from .models import Poll 

class CreateView(generic.edit.CreateView): 
    model=Poll 
    fields=['description', 'maxVar', 'minVotes'] 

我想讓自己熟悉Django。這個問題可以通過用自定義的clean()方法編寫FormView來解決。但我想知道爲什麼這不起作用,理想情況下,如何解決問題。

我使用Django 1.8和Python 2.7.8。

+0

你可以包含你正在使用的Django和Python的版本嗎? –

回答

0

初始值僅用於兩個目的:在html表單輸入中呈現初始值,並查看提交的值是否已更改。它不用於驗證表單:不將實際數據傳遞給表單與將初始數據顯式更改爲空值相同。

由於您的maxVarminVotes字段是必需的(它們沒有blank=True),因此不允許刪除初始值並將任何數據傳遞到表單。如果你想要驗證表單,你必須通過它們。

+0

謝謝,這很有幫助。 有沒有一種標準方法來測試用戶必須設置的最小字段,而無需進行實時服務器測試? – GammaSQ