寫測試用例來測試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
如何解決它。
什麼不好嗎理解?錯誤消息非常明確:'self.instance'中的用戶沒有'user_profile',但您正在嘗試使用它。 – spectras
[如何測試django模型窗體?](http://stackoverflow.com/questions/31046998/how-to-test-django-model-form) – stellasia