Problem with Django forms and cache control
I'm populating the choices of a form choicefield in django, it's a year select field. I get the years from the database and put them in a list of tuples in the field. My code looks like this
def get_years():
choices = []
years = []
for poll in Poll.objects.all().order_by('created'):
y开发者_Python百科ears.append(poll.created.year)
for year in list(set(years)):
choices.append((year, year))
return choices
and my form field looks like this
year = forms.ChoiceField(choices=get_years())
The problem is that when I see it in the browser, the year list is fine according to the database, but when I change some date in database, the year select list doesn't update. I've tried width @cache_control(no_cache=True)
decorator, but doesn't work. Any ideas?
Thanks in advance!
Update the years when you initialize a form instance.
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['year'].choices = self.get_years()
精彩评论