Search code examples
djangodjango-formsdjango-testingdjango-unittestdjango-tests

form.is_valid() failing in Django unit test


I'm running a unit test for a Django form, and form.is_valid() keeps returning False and I cannot find the error.

Here's the code for 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']

And here's the code for tests.py:

class NewQuestionFormTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        FossCategory.objects.create(name = 'TestCategory', email = '[email protected]')

    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())

This is what I get with 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>

Solution

  • Since it's a model choice field, try using the primary key of the category instead of the instance itself.

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