[Answer]-Select choices on form field

1๐Ÿ‘

โœ…

You can dynamically modify the choices in the form init by passing the environment variable to the form:

views.py

form = AnimalInfoForm(environment)

forms.py

ANIMAL_TYPE_CHOICE = (
    (1, 'Lion'),
    (2, 'Tiger'),
    (3, 'Dolphin'),
    (4, 'Shark'),
)

ANIMAL_TYPE_CHOICE_AFRICA = (
    (1, 'Lion'),
    (2, 'Tiger'),
    (3, 'Elephant'),
    (4, 'Monkey'),
)

class AnimalInfoForm(forms.Form):
    animal_type = forms.Field()
    def __init__(self, environment, *args, **kwargs):
       super(AnimalInfoForm, self).__init__(*args, **kwargs)
       if environment == "Africa":
           self.fields['animal_type'] = forms.ChoiceField(choices=ANIMAL_TYPE_CHOICE_AFRICA))
       else:
            self.fields['animal_type'] = forms.ChoiceField(choices=ANIMAL_TYPE_CHOICE))
๐Ÿ‘คThomas Kremmel

0๐Ÿ‘

You should modify the choices attribute of your form field widget.

Leave a comment