0

我有一个带有新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,它会完美运行。)

谢谢 !

4

1 回答 1

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等)。

于 2012-08-22T22:24:09.317 回答