Django,验证表单
我希望我的表单是动态的,对于IntegerField,一些参数sucj as max_length因型号而异。 通过使用这里的信息,我写下了这个表格:
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)if form.is_valid()
没有理由这样做。 你让事情变得不必要的复杂。
不是将初始值传递给返回带有预定义类的工厂函数,而是在表单定义中省略初始参数,并在表单实例化时将其传入:
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})
链接地址: http://www.djcxy.com/p/56551.html