尝试测试Django表单时出错

时间:2014-11-03 18:20:07

标签: django

我正在尝试为此表单编写测试:

class UserCreateForm(forms.ModelForm):
    email = forms.EmailField(label=_("Email"), max_length=254, required=True)
    is_admin = forms.BooleanField(required=False)
    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
                                widget=forms.PasswordInput,
                                help_text=_("Enter the same password as above, for verification."))

    permissions = PermissionMultipleChoiceField(queryset=Permission.objects.filter(content_type=ContentType.objects.get_for_model(get_user_model()),
                                                                                   codename__regex='^can_(view|manage)_.*'),
                                                widget=CheckboxSelectMultiple)

但是当我这样做时,我收到了这个错误:

Traceback (most recent call last):
  (...)
  File "/Users/tapia/src/axpo-em/energymanager/adminpanel/forms.py", line 55, in <module>
    class UserCreateForm(forms.ModelForm):
  File "/Users/tapia/src/axpo-em/energymanager/adminpanel/forms.py", line 64, in UserCreateForm
    permissions = PermissionMultipleChoiceField(queryset=Permission.objects.filter(content_type=ContentType.objects.get_for_model(get_user_model()),
  (...)
OperationalError: no such table: django_content_type

奇怪的是,如果我粘贴在测试中引发错误的查询集,它就可以完美地运行:

class UserCreateFormTest(TestCase):
    def test_user_create_form(self):
        print ContentType.objects.get_for_model(Client)
        print Permission.objects.filter(content_type=ContentType.objects.get_for_model(get_user_model()),
                                  codename__regex='^can_(view|manage)_.*')

这让我发疯了。请问有什么想法吗?

更新

我已经看到,如果我以这种方式编写测试,它工作正常,但我不知道为什么,而且似乎错了(我应该为每个测试方法进行导入吗?) :

class UserCreateFormTest(TestCase):
    def test_user_create_form(self):

        # Why does the import must be inside the test method????
        from adminpanel.forms import UserCreateForm

        form = UserCreateForm(data={})

0 个答案:

没有答案