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.
这是我的表格。编写测试用例:
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
当我测试给出此错误的表单时:
user_profile = self.instance.user_profile 文件“/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py”,第343行,获取
raise self.field.rel.to.DoesNotExist
DoesNotExist
如何解决?
答案 0 :(得分:0)
Simply creating model object will not create the record in the database.
Use .objects.create
to create a record.
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()
)
or use save
:
test_filter = Filter(...)
test_filter.save()