Django Forms, Choices and Caching

Some of the drop down menus on my forms require a bunch of database hits. To speed things up and reduce the load on my database, I use Django’s low level caching to hold those menus. To keep the cache fresh, I add code to clear the cache in the save method of the model. Nothing out of the ordinary here. So why weren’t my menus updating when the model changed???

My first thought was there was something wrong with my code to delete the cache. I was using the cache.delete(key) command. Some debug statements showed that was not the problem. They also showed that my method for generating the menu was not being called either. Odd…

Then I remembered I was setting the form choices when I was creating class variables. The class and those variables are created once when the server is started. Here was the offending code:

from django import forms

class MyForm(forms.Form):
    my_choice_field = forms.ChoiceField(choices=my_model.make_choices())

The problem was solved by moving the choices code to inside the __init__ method:

from django import forms

class MyForm(forms.Form):
    my_choice_field = forms.ChoiceField(choices=[])

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['my_choice_field'].choices = my_model.make_choices()