Django,验证表格

时间:2010-02-21 20:16:06

标签: django django-forms

我希望我的表单是动态的,IntegerField的一些参数为max_length,因模型而异。通过使用here中的信息,我写了这样的表格:

def my_form(inputname, inputlastname, inputamount):
 class MyForm(forms.Form):
  name = forms.CharField(max_length=50,required=True,initial=inputname)
  lastname = forms.CharField(max_length=50, required=True,initial=inputlastname)
  amount= forms.IntegerField(max_value=inputamount, required=True)
 return MyForm

当我像这样调用它并传递给模板时,它在模板上渲染得很好:

form = my_form("David","Bowie",4)()

但是我无法弄清楚如何验证它,这失败了:

如果request.method =='POST':   form = MyForm(request.POST)   如果form.is_valid()

1 个答案:

答案 0 :(得分:4)

没有理由这样做。你的事情变得不必要了。

不是将初始值传递给返回具有预定义类的类的工厂函数,而是在表单定义中省略初始参数,并在表单实例化期间传递它们:

class MyForm(forms.Form):
    name = forms.CharField(max_length=50,required=True)
    lastname = forms.CharField(max_length=50, required=True)

...

form = MyForm(request.POST, initial={'firstname':myfirstname, 'surname':mysurname})

在追加问题后修改

为了获得金额的动态max_value,您可以覆盖表单的__init__方法并将其设置在那里。然后再次在实例化中传递值。

class MyForm(forms.Form):
    name = forms.CharField(max_length=50,required=True)
    lastname = forms.CharField(max_length=50, required=True)
    amount = forms.IntegerField(required=True)

    def __init__(self, *args, **kwargs):
        amount_max = kwargs.pop('amount_max', None)
        super(MyForm, self).__init__(*args, **kwargs)
        if amount_max:
            self.fields['amount'].max_value = amount_max

...

form = MyForm(request.POST, amount_max=10,
              initial={'firstname':myfirstname, 'surname':mysurname})