当使用 Django 时,如果 required=False,会自动生成ModelChoiceField
一个额外的选项。('', '--------')
选择此选项时,它None
以cleaned_data
. 使用常规时如何(惯用地)重现此行为ChoiceField
?
我注意到的一些事情:
- 我还没有找到任何自动将元组添加
('', '---------')
到列表中的方法choices
,因此似乎需要手动添加它。我觉得应该有一种方法可以通过不同地设置其中一个参数来将其添加到选择中,所以如果存在的话,我很想听听。 - 从
''
to的转换None
仍然必须在使用cleaned_data
. 这意味着处理ModelChoiceField
s 的代码必须与代码略有不同ChoiceField
,这可能会导致细微的错误。再说一遍:如果有人知道更好的成语,我很想听听。 TypedChoiceField
对''
. 特别是,它没有coerce
像人们期望的那样将其提供给功能。
考虑以下代码:
def int_or_none(s):
if s.isnumeric():
return int(s)
return None
class NoneForm(forms.Form):
field = forms.TypedChoiceField(
choices=[('', '--------'), ('1', 'One'), ('2', 'Two')],
required=False, coerce=int_or_none)
def home(request):
if request.method == "POST":
form = NoneForm(request.POST)
if form.is_valid():
assert type(form.cleaned_data['field']) in [int, type(None)]
print form.cleaned_data['field']
form = NoneForm()
return HttpResponse(
"""<form method="POST">""" +
form.as_table() +
"""<input type="submit"></form>""")
上面的断言失败了!
以惯用的方式ChoiceField
清理Django 的各种版本真的很难吗?None