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()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s