在Django单元测试中form.is_valid()失败

时间:2018-06-15 09:31:45

标签: django django-forms django-testing django-unittest django-tests

我正在为Django表单运行单元测试,form.is_valid()不断返回False,我找不到错误。

这里是forms.py的代码:

class CustomClearableFileInput(forms.ClearableFileInput):
    template_name = 'forums/templates/clearable_file_input.html'

class NewQuestionForm(forms.ModelForm):

    category = forms.ModelChoiceField(widget = forms.Select(attrs = {}),
                        queryset = FossCategory.objects.order_by('name'),
                        empty_label = "Select a Foss category",
                        required = True,
                        error_messages = {'required':'Select a category'})

    title = forms.CharField(widget = forms.TextInput(),
                        required = True,
                        error_messages = {'required':'Title field required'},
                        strip=True)

    body = forms.CharField(widget = forms.Textarea(),
                        required = True,
                        error_messages = {'required':'Question field required'},
                        strip=True)

    is_spam = forms.BooleanField(required = False)

    spam_honeypot_field = HoneypotField()

    image = forms.ImageField(widget = CustomClearableFileInput(), help_text = "Upload image", required = False)

    def clean_title(self):
        title = str(self.cleaned_data['title'])

        if title.isspace():
            raise forms.ValidationError("Title cannot be only spaces")
        if len(title) < 12:
            raise forms.ValidationError("Title should be longer than 12 characters")
        if Question.objects.filter(title = title).exists():
            raise forms.ValidationError("This title already exist.")

        return title

    def clean_body(self):

        body = str(self.cleaned_data['body'])
        if body.isspace():
            raise forms.ValidationError("Body cannot be only spaces")
        if len(body) < 12:
            raise forms.ValidationError("Body should be minimum 12 characters long")
        body = body.replace('&nbsp;', ' ')
        body = body.replace('<br>', '\n')

        return body

    class Meta(object):

        model = Question
        fields = ['category', 'title', 'body', 'is_spam', 'image']

这里是tests.py的代码:

class NewQuestionFormTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        FossCategory.objects.create(name = 'TestCategory', email = 'example@example.com')

    def test_too_short_title(self):
        category = FossCategory.objects.get(name = "TestCategory")
        title = 'shorttitlefsodzo'
        form = NewQuestionForm(data = {'category': category, 'title': title, 'body': 'Test question body'})
        self.assertTrue(form.is_valid())

这是print(form.errors)所得到的:

<ul class="errorlist"><li>category<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li>

1 个答案:

答案 0 :(得分:1)

由于它是模型选择字段,请尝试使用类别的主键而不是实例本身。

form = NewQuestionForm(data = {'category': category.pk, 'title': title, 'body': 'Test question body'})