Darwin Tech
Darwin Tech

Reputation: 18919

Select choices on form field

I have a Django form which takes a CHOICE tuple:

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

class AnimalInfoForm(forms.Form):
    ...
    animal_type = forms.ChoiceField(
        choices=ANIMAL_TYPE_CHOICE,
    )

What I want to do though, is offer a different choice selection based on named url patterns.

So in my view I I have something like this:

 def AnimalInfo(request, environment=None):
      ...
      

What I need help with is offering different choice options depending on the environment variable. For example:

 def AnimalInfo(request, environment=None):
      ...
     if environment == 'marine':
         # only offer choices 3,4
         ANIMAL_TYPE_CHOICE = (
             (3, 'Dolphin'),
             (4, 'Shark'),
         )

How can I dynamically configure the choices like this based on the request?

Upvotes: 0

Views: 1157

Answers (2)

Thomas Kremmel
Thomas Kremmel

Reputation: 14783

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

Upvotes: 1

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

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

Upvotes: 0

Related Questions