I've got a ModelForm that I've modified such that it returns a tuple for an option group multiselect on the displayed form. Tuple is structured like this:
(
('Alabama', (
('1', 'Item 1'),
('2', 'Item 2'),
)
),
('Alaska', (
('3', 'Item 3'),
('4', 'Item 4'),
)
),
)
The problem I've run into is that the underlying data that makes up the contents of the choices tuple might change (Item 5 might be added or Item 4 may be deleted) but the tuple never gets updated - presumably because Django knows tuples are immutable and my get_tree_data() function never gets called after the server starts for the first time. How do I override that behavior? My code is below:
def get_tree_data():
sp = StateProvince.objects.all().values('state_province').order_by('state_province')
my_dict = OrderedDict()
for i in sp:
for k in Location.objects.filter(state_province__state_province=i['state_province']):
try: my_dict[i['state_province']].append([k.id, k.name])
except KeyError: my_dict[i['state_province']] = [[k.id, k.name]]
return tuple([(key, tuple([(a, b) for a, b in value])) for key, value in my_dict.iteritems()])
class SchedulerProfileForm(ModelForm):
locations = MultipleChoiceField(choices=get_tree_data())
class Meta:
model = SchedulerProfile
EDIT Per the accepted answer, code:
class SchedulerProfileForm(ModelForm):
def __init__(self, *args, **kwargs):
super(SchedulerProfileForm, self).__init__(*args, **kwargs)
self.fields['locations'] = MultipleChoiceField(choices=get_tree_data())
class Meta:
model = SchedulerProfile