如何禁用Django表单中的queryset缓存?
问题描述:
我有应该过滤,只有通过查询集选择一个Django形式:如何禁用Django表单中的queryset缓存?
class GenerateStudentAttendanceForm(forms.Form):
selected_class = forms.ModelChoiceField(queryset=Class.on_site.filter(
is_active=True,
academic_year__is_active=True
))
date = forms.DateField(initial=now().date())
的问题是,当窗体被实例化并用于即使网站已经改变后续请求Class.on_site.filter
进行评估。
我该如何解决这个问题?
答
您可以通过覆盖Form
类的构造函数来实例化该字段,以便在窗体的每个实例化上评估queryset。
class GenerateStudentAttendanceForm(forms.Form):
date = forms.DateField(initial=now().date())
def __init__(self, *args, **kwargs):
super(GenerateStudentAttendanceForm, self).__init__(*args, **kwargs)
# add the key `selected_class` to the dictionary of `fields`
self.fields['selected_class'] = forms.ModelChoiceField(queryset=Class.on_site.filter(
is_active=True,
academic_year__is_active=True
))
+1
看起来你需要先调用'super(GenerateStudentAttendanceForm,self).__ init __(* args,** kwargs)',否则你会得到''GenerateStudentAttendanceForm'对象没有属性'fields''。 –
+0
对。我只在我的项目中实现了这种方式。 –
你是说即使其中一个Class对象被删除,它仍然可以在下拉菜单中使用吗? –
@SandeepBalagopal我没有试过,但似乎是这样,因为显示的类是从默认网站。 –
你需要显示'on_site'是什么。 –