我有一个带有新init方法的表单,它允许根据参数显示各种选择:
class Isochrone_Set_Parameters(forms.Form):
Grid_Choices = Grids_Selection.Grid_Choices
def __init__(self, Grid_Type, *args, **kwargs):
super(Isochrone_Set_Parameters, self).__init__(*args, **kwargs)
if Grid_Type == Grids_Selection.Grid_Values[0]:
Choices = (('0.0','0.0'),('0.1','0.1'),('0.3','0.3'),('0.5','0.5'),('0.6','0.6'),('0.7','0.7'), \
('0.8','0.8'),('0.9','0.9'),('0.95','0.95'))
self.fields['Rotation_Rate'] = forms.ChoiceField(choices=Choices)
elif Grid_Type == Grids_Selection.Grid_Values[1]:
Choices = (('0.0','0.0'),('0.568','0.568'))
self.fields['Rotation_Rate'] = forms.ChoiceField(choices=Choices)
else:
Choices = (('-1.0','-1.0'),('-2.0','-2.0'))
self.fields['Rotation_Rate'] = forms.ChoiceField(choices=Choices)
self.fields.keyOrder = [
'Selected_Grid',
'Metallicity',
'Mass',
'Rotation_Rate']
Selected_Grid = forms.ChoiceField(choices=Grid_Choices)
Metallicity = forms.FloatField()
Mass = forms.FloatField()
和以下观点:
def Isochrone(request):
if request.method == 'POST':# If the form has been submitted...
form = Isochrone_Set_Parameters(request.POST) # A form bound to the POST data
if form.is_valid():
return HttpResponse("C'est ok")
else:
return render_to_response("Site/Isochrone.html",{
'form': form
},context_instance=RequestContext(request))
else:
form = Isochrone_Set_Parameters(Grid_Type = "NotSet",initial={'Metallicity': -1.0, 'Mass': -1.0, 'Rotation_Rate': -1.0}) # An unbound form
return render_to_response("Site/Isochrone.html",{
'form': form
},context_instance=RequestContext(request))
发布表单时,form.is_valid() 测试失败。我没有错误消息,并且可以通过 form.POST.["My_Value"] 访问发布的值。我不明白我做错了什么。有人可以告诉我如何纠正这个问题吗?
(我准确地说,该错误似乎与表单中init方法的重载有关,因为如果我为 Rotation_Rate 放置一个简单的 ChoiceField,它会完美运行。)
谢谢 !