[ACCEPTED]-How to set choices in dynamic with Django choicefield?-django

Accepted answer
Score: 24

I often set the choices dynamicly in the 1 constructor:

class MyForm(BaseForm):
    afield = forms.ChoiceField(choices=INITIAL_CHOICES)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['afield'].choices = my_computed_choices
Score: 3

The key is to realise that choices can be any iterable:

import uuid
from itertools import count
class MyForm(BaseForm):

    counter = count(1)

    def my_choices():
        yield (uuid.uuid1, next(counter)) 

    afield = forms.ChoiceField(choices=my_choices)

Or 1 whatever logic you like inside my_choices.

Score: 2

In a view you could do the following


lstChoices = _getMyChoices()

form.fields['myChoiceField'].choices = lstChoices

where 2 lstChoices is list of dynamically generated 1 tuples for your choices.

Score: 0

Use the constructor to set dynamic choices 4 as shown below:

class DateForm(forms.ModelForm):    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Write the code here to set dynamic choices

        self.fields['month'].choices = dynamic_choices

In addition, I recommend 3 to add the empty label '("", "---------")' to dynamic choices so that the dynamic 2 choices works properly as the default behavior 1 of the select box in Django.

More Related questions