[ACCEPTED]-How to set choices in dynamic with Django choicefield?-django
Accepted answer
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
The key is to realise that choices
can be any iterable:
import uuid
from itertools import count
class MyForm(BaseForm):
counter = count(1)
@staticmethod
def my_choices():
yield (uuid.uuid1, next(counter))
afield = forms.ChoiceField(choices=my_choices)
Or 1 whatever logic you like inside my_choices
.
In a view you could do the following
--views.py
lstChoices = _getMyChoices()
form.fields['myChoiceField'].choices = lstChoices
where 2 lstChoices is list of dynamically generated 1 tuples for your choices.
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.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.