2015-06-26 60 views
-1

寫測試用例來測試FilterForm如何在django中測試模型表單?

class MyTestCreateFilter(TestCase): 

    def test_createfilter(self): 
    self.client = Client()  
    self.user = User.objects.create_superuser(username='bizi111',email='[email protected]',password='bizi111') 
    self.user = authenticate(username='bizi111', password='bizi111') 
    #print self.user 
    self.factory = RequestFactory() 
    request = self.factory.get('/filter/new') 
    request.user = self.user 
    response = create_or_edit_filter(request) 
    self.assertEqual(response.status_code, 200) 

    filterform = FilterForm() 
    #print filterform.is_valid() 
    form_data = {'keyword': 'it','industry':'it','zip_code':'50005','distance':30} 

    filteform = FilterForm(form_data) 

    self.assertEqual(filteform.is_valid(), True) 

FilterForm有一個乾淨的方法:

def clean(self): 
     #print self.instance.user_profile 
     user_profile = self.instance.user_profile 
     keyword = self.cleaned_data.get("keyword") 
     if Filter.objects.filter(user_profile=user_profile, keyword=keyword).exclude(id=self.instance.id).count() > 0: 
      msg = u"A filter with that keyword already exists!" 
      self._errors["keyword"] = self.error_class([msg]) 

     return self.cleaned_data 

給這個錯誤:

File "/home/suma/workspace2/bizintro/bizintro/forms.py", line 80, in clean user_profile = self.instance.user_profile File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 343, in get raise self.field.rel.to.DoesNotExist DoesNotExist

如何解決它。

+1

什麼不好嗎理解?錯誤消息非常明確:'self.instance'中的用戶沒有'user_profile',但您正在嘗試使用它。 – spectras

+0

[如何測試django模型窗體?](http://stackoverflow.com/questions/31046998/how-to-test-django-model-form) – stellasia

回答

0

表單似乎是一個結合的形式,這意味着它應該有連接到它的一些模型的實例。而事實並非如此。

https://docs.djangoproject.com/en/1.8/topics/forms/#bound-and-unbound-form-instances

因爲我不知道是什麼樣的模式,這是應該的,我不能告訴你太多,但你要添加的東西,看起來像:

filterform = FilterForm() 
#print filterform.is_valid() 
form_data = {'keyword': 'it','industry':'it','zip_code':'50005','distance':30} 

filterform = FilterForm(form_data) 

filterform.instance = # Some object here... 


self.assertEqual(filterform.is_valid(), True)