【问题标题】:how to test django model form?如何测试 django 模型形式?
【发布时间】:2015-06-25 09:56:11
【问题描述】:

我写了一个测试用例:

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.

这是我的表格。如何编写测试用例:

类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 get

中的文件“/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py”,第 343 行
raise self.field.rel.to.DoesNotExist

不存在

如何解决?

【问题讨论】:

  • add 模型可能对您的问题有用。以及完整的回溯。
  • 不。它对我不起作用。给出同样的错误

标签: django


【解决方案1】:

仅创建模型对象不会在数据库中创建记录。

使用.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()
)

或使用save:

test_filter = Filter(...)
test_filter.save()

【讨论】:

    猜你喜欢
    • 2011-11-09
    • 2021-12-18
    • 1970-01-01
    • 2021-01-04
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    相关资源
    最近更新 更多