conditionally change widget type in django form

1.5k views Asked by At

I have the following simple form:

class ContactEmailForm(forms.ModelForm):

    subject = forms.ChoiceField(choices=SUBJECT_TYPES)

    class Meta:
        model = ContactEmail
        fields = ('name', 'email', 'subject', 'message',)

I want to conditionally change the subject field between a choice field and text input field.

How can I do this?

1

There are 1 answers

1
Kevin Cherepski On

This could be accomplished by overriding the __init__ function within your ContactEmailForm class.

class ContactEmailForm(forms.ModelForm):

    subject = forms.ChoiceField(choices=SUBJECT_TYPES)

    def __init__(self, *args, **kwargs):
        super(ContactEmailForm, self).__init__(*args, **kwargs)
        if YOURCONDITION:
            self.fields['subject'] = forms.CharField()

    class Meta:
        model = ContactEmail
        fields = ('name', 'email', 'subject', 'message',)