如何测试Django模型的形式? [英] how to test django model form?
本文介绍了如何测试Django模型的形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个测试用例:
class MyTestCreateFilter(TestCase):
def test_createfilter(self):
test_filter = Filter(user_profile_id= 3,
keyword = 'ca',
industry = 'it',
zip_code = '50002',
distance = 30,
creation_date = datetime.date.today(),
last_run_date = datetime.date.today()
)
test_filter_form = FilterForm(instance=test_filter)
self.assertEqual(test_filter_form.is_valid(), False)#without data
test_filter_form = FilterForm({'user_profile_id':3,'keyword': 'ca','industry':'it','zip_code':'50002','distance':30,'creation_date': datetime.date.today(),
'last_run_date': datetime.date.today() }, instance=test_filter)
print test_filter_form.is_valid()
给出错误:
DoesNotExist: UserProfile matching query does not exist.
这是我的表单.如何编写测试用例:
this is my form.how to write test case:
FilterForm(forms.ModelForm)类:
class FilterForm(forms.ModelForm):
class Meta:
model=Filter
exclude=('user_profile','creation_date','last_run_date')
widgets = {
'zip_code': forms.TextInput(attrs={'placeholder': "e.g. 20708"}),
}
def clean(self):
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
当我测试给出此错误的表格时:
when i test the form giving this error:
user_profile = self.instance.user_profile获取
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
DoesNotExist
如何解决?
推荐答案
仅创建模型对象不会在数据库中创建记录.
Simply creating model object will not create the record in the database.
使用 .objects.create
创建记录.
test_filter = Filter.objects.create(
user_profile_id= 3,
keyword = 'ca',
industry = 'it',
zip_code = '50002',
distance = 30,
creation_date = datetime.date.today(),
last_run_date = datetime.date.today()
)
或使用保存
:
test_filter = Filter(...)
test_filter.save()
这篇关于如何测试Django模型的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文