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

标签 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 = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e2ffe6eaf7ebe2c7e2ffe6eaf7ebe2a9e4e8ea" rel="noreferrer noopener nofollow">[email protected]</a>')

    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>

最佳答案

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

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

关于django - form.is_valid() 在 Django 单元测试中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50872785/

相关文章:

python - 如何测试 Django QuerySets 是否相等?

python - django-sendgrid-v5 一切似乎都正常,但邮件没有送达

python - 如何使用django将文件上传到服务器?

python - Tinymce 未显示在 django 管理中

python - 如何覆盖自定义 UserChangeForm 中用户名的 django 'unique' 错误消息

python - 为什么在创建模型表单时需要 "class Meta"?

python - 使用 django_nose 和 django-dynamic-fixture 优化示例 django 模型的设置和拆卸

django - Django 中单元测试的 auth_token

python - Django 中唯一标识多对多关系

Django 表单 request.user