验证一个重载_init_的表单 [英] Validating a form with overloaded _init_

查看:110
本文介绍了验证一个重载_init_的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个新的 init 方法的表单,它允许根据参数显示各种选择:

 code> 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)

如果Grid_Type == Grids_Selection.Grid_Values [0]:
选择=(('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'] = form.ChoiceField(choices = Choices)
elif Grid_Type == Grids_Selection.Grid_Values [1]:
选择=(('0.0','0.0'),('0.568','0.568'))
self.fields ['Rotation_Rate'] = forms.ChoiceF ield(choices = Choices)
else:
选择=(('-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()
质量= forms.FloatField )

和以下视图:

  def Isochrone(request):
如果request.method =='POST':#如果表单已经提交...
form = Isochrone_Set_Parameters(request.POST )#一个绑定到POST数据的表单

如果form.is_valid():

返回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 = {'Metallicity':-1.0,'Mass':-1.0,'Rotation_Rate':-1.0})#未绑定的形式

返回render_to_response(Site / Isochrone.html,{
'form':form
},context_instance = RequestContext(request))

表单发布,form.is_valid()测试失败。我没有错误消息,并且发布的值可以通过form.POST。[My_Value]访问。我不明白我在做错什么有人可以给我一个关于如何纠正这个问题的提示吗?



(确切的说,错误似乎与 init 方法的形式,因为如果我放一个简单的ChoiceField为Rotation_Rate,它的工作完美。)



谢谢!

解决方案

您已将签名更改为表单初始化,因此第一个参数现在为 Grid_Type 而不是通常的数据。这意味着当您执行 form = Isochrone_Set_Parameters(request.POST)时,POST用于 Grid_Type 。 / p>

确保您始终通过 Grid_Type ,或(最好)不要将它放在参数列表中:从 kwargs

  def __init __(self,* args ,** kwargs):
Grid_Type = kwargs.pop('Grid_Type',无)
super(Isochrone_Set_Parameters,self).__ init __(* args,** kwargs)
...

(另外,请使用PEP8标准命名约定: IsochroneSetParameters grid_type 等)。


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 !

解决方案

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).

这篇关于验证一个重载_init_的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆