Django表单与缓存控制的问题
我在Django中填充一个表单的选择字段,这个字段是用来选择年份的。我是从数据库中获取年份,然后把它们放进一个元组列表里。我的代码看起来是这样的:
def get_years():
choices = []
years = []
for poll in Poll.objects.all().order_by('created'):
years.append(poll.created.year)
for year in list(set(years)):
choices.append((year, year))
return choices
而我的表单字段看起来是这样的:
year = forms.ChoiceField(choices=get_years())
问题是,当我在浏览器中查看时,年份列表是根据数据库显示的没错,但当我在数据库中更改了一些日期后,年份选择列表却没有更新。我试过使用 @cache_control(no_cache=True)
这个装饰器,但没有效果。有没有什么好的建议呢?
提前谢谢大家!
1 个回答
11
在你初始化一个表单实例的时候,更新年份。
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['year'].choices = self.get_years()