我有一张表格
class UploadForm(forms.Form):
#...
src_lang = forms.ChoiceField(choices=settings.LANGUAGES)
tgt_lang = forms.ChoiceField(choices=settings.LANGUAGES)
并以这种方式设置src_lang
的初始值:
uploadform = UploadForm(initial={'src_lang':'de'})
return render(request, 'upload.html', {'form':uploadform})
到目前为止,这么好。
现在我需要在渲染到模板之前从'de'
过滤掉tgt_lang
(以便tgt_lang
不显示它)。我该怎么做?
答案 0 :(得分:2)
您必须覆盖UploadForm
的构造函数。像这样:
class UploadForm(forms.Form):
...
def __init__(self, *args, **kwargs):
super(UploadForm, self).__init__(*args, **kwargs)
src_lang = self.initial.get('src_lang')
if src_lang:
choices = [(code, lang) for (code, lang) in settings.LANGUAGES
if code != src_lang]
self.fields['tgt_lang'].choices = choices
self.fields['tgt_lang'].widget.choices = choices