1

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?

Atma
  • 29,141
  • 56
  • 198
  • 299

1 Answers1

1

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',)
Kevin Cherepski
  • 1,473
  • 8
  • 8