问题
I have a form with a new init method, which allow to display various choices according to a parameter :
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()
and the following view :
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))
When the form is posted, the form.is_valid() test failed. I have no error messages, and the posted value are accessible through form.POST.["My_Value"]. I don't understand what I am doing wrong. Can somebody give me a hint on how to correct this ?
(I precise that the error seems to be linked to the overloading of the init method in the form, because if I put a simple ChoiceField for Rotation_Rate, it works perfectly.)
Thanks !
回答1:
You've changed the signature to the form initialization, so that the first parameters is now Grid_Type
rather than the usual data
. This means that when you do form = Isochrone_Set_Parameters(request.POST)
, the POST is being used for Grid_Type
.
Either make sure you always pass Grid_Type
, or (preferably) don't put that in the parameter list at all: get it from kwargs
:
def __init__(self, *args, **kwargs):
Grid_Type = kwargs.pop('Grid_Type', None)
super(Isochrone_Set_Parameters, self).__init__(*args, **kwargs)
...
(Also, please use PEP8-standard naming conventions: IsochroneSetParameters
, grid_type
, etc).
来源:https://stackoverflow.com/questions/12081628/validating-a-form-with-overloaded-init