我有一个带有新 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,它就可以完美地工作。)
谢谢!
答案 0 :(得分:0)
您已将签名更改为表单初始化,因此第一个参数现在为Grid_Type
,而不是通常的data
。这意味着当您执行form = Isochrone_Set_Parameters(request.POST)
时,POST将用于Grid_Type
。
要么确保你总是通过Grid_Type
,要么(最好)不要把它放在参数列表中:从kwargs
获取它:
def __init__(self, *args, **kwargs):
Grid_Type = kwargs.pop('Grid_Type', None)
super(Isochrone_Set_Parameters, self).__init__(*args, **kwargs)
...
(另外,请使用PEP8标准命名约定:IsochroneSetParameters
,grid_type
等。)