This is similar to a situation where you could take advantage of the trick that Ilian Iliev blog deals with, Django forms a ChoiceField with dynamic values ....
Iliev shows a very similar initializer:
my_choice_field = forms.ChoiceField(choices=get_my_choices())
He says: "The trick is that in this case, my_choice_field parameters are initialized when the server starts (re). Or, in other words, after the server starts, the selection is loaded (calculated) and they will not change until the next (re) Start." It looks like the same difficulty you are facing.
His trick: “Fortunately, the form class has an init method that is called each time the form is loaded. In most cases, you skipped it in the form definition, but now you have to use it.”
Here is his sample code mixed with a generator expression:
class MyForm(forms.Form): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['my_choice_field'] = forms.ChoiceField( choices=( (i, ungettext_lazy('%s thing', '%s things', i) % i) for i in range(1,4) )
The generator expression is enclosed in parentheses so that it is treated as a generator object to which choices assigned.
NB I have not tried this code in Django. I just convey the idea of Iliev.
Jim DeLaHunt
source share