【发布时间】:2014-07-10 13:21:12
【问题描述】:
我有一个 django ModelChoiceField,如果我覆盖查询集,它将无法验证。
class PersonalNote(forms.Form):
tile = ModelChoiceField(queryset=Tile.objects.none())
note = forms.CharField()
form = PersonalNote()
form.fields['tile'].queryset = Tile.objects.filter(section__xxx=yyy)
form.is_valid() 错误是:“选择一个有效选项。该选项不是可用选项之一”。
如果 Tile.objects.none() 被替换为 Tile.objects.all() 它会验证,但会从数据库加载太多数据。我也试过:
class PersonalNote(forms.Form):
tile = ModelChoiceField(queryset=Tile.objects.none())
note = forms.CharField()
def __init__(self, *args, **kwargs):
yyy = kwargs.pop('yyy', None)
super(PersonalNote, self).__init__(*args, **kwargs)
if yyy:
self.fields['tile'].queryset = Tile.objects.filter(section__xxx=yyy)
这里可能有什么问题?请注意,实际应用程序也会覆盖标签,但这似乎不是一个因素:
class ModelChoiceField2(forms.ModelChoiceField):
def label_from_instance(self, obj):
assert isinstance(obj,Tile)
return obj.child_title()
【问题讨论】:
标签: django validation django-forms