Search code examples
djangodjango-formsdjango-testingdjango-widget

Testing Form Field Widget Type


I'm writing tests form a Django model form:

class TemplateFieldTextForm(forms.ModelForm):
    class Meta:
        model = TemplateFieldText
        fields = []

    def __init__(self, *args, **kwargs):
        super(TemplateFieldTextForm, self).__init__(*args, **kwargs)
        field = self.instance.template_field
        label = field.label or var_to_proper(field.identifier)

        if field.input_type == 'text_area':
            self.fields['text'] = forms.CharField(label=label, required=field.required, widget=forms.Textarea)
        else:
            self.fields['text'] = forms.CharField(label=label, required=field.required)

I am trying to test that the correct widget for the text field gets set, like so:

def test_submit_with_char_field(self):
    template_field = mommy.make(TemplateField, label='char_field')
    template_field_text = mommy.make(TemplateFieldText, template_field=template_field,
                                     award_process=self.award_process)
    form_data = {
        'text': 'some text'
    }
    form = TemplateFieldTextForm(form_data, instance=template_field_text)
    self.assertEqual(form.fields['text'].widget.__class__.__name__, 'TextInput')

However, the widget seems to always be the Textarea widget, rather than the default TextInput. When I check the form in the actual rendered template, the form does indeed change as expected. Any ideas as to where I am going wrong in the tests?


Solution

  • It turns out I was setting the incorrect model field value.

    template_field = mommy.make(TemplateField, label='char_field')
    

    should be:

    template_field = mommy.make(TemplateField, input_type='char_field')