Django在运行时形成integerField set max_value

时间:2010-08-12 18:20:08

标签: django forms django-forms

我有一个这样的表格:

class SomeForm(forms.Form):
 first = forms.IntegerField(max_value= DontWantToSetYet)
 second = forms.IntegerField(max_value= DontWantToSetYet)
 third = forms.IntegerField(max_value= DontWantToSetYet)

如何在运行时设置max_values?即

if request.method == 'POST':
    form = SomeForm(request.POST, max_values = {'first':10,'second':50,'third':666})
    [...]

2 个答案:

答案 0 :(得分:5)

您可以在__init__方法中设置字段的最大值,如此处所示

class SomeForm(forms.Form):
    def __init__(self, max_values, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        self.fields['first'] = forms.IntegerField(max_value=max_values['first'])
        ...

    first = forms.IntegerField(max_value= DontWantToSetYet)
    second = forms.IntegerField(max_value= DontWantToSetYet)
    third = forms.IntegerField(max_value= DontWantToSetYet)

编辑:

self.fields['first'].max_value = max_values['first']
当我尝试时,

没有用,重新定义像这样的字段定义

self.fields['first'] = forms.IntegerField(max_value=max_values['first'])

答案 1 :(得分:1)

在阅读django来源后,我想出了类似的东西:

def __init__(self, max_values, *args, **kwargs):
    super(SendFleetFormOne, self).__init__(*args, **kwargs)
    for name, value in max_values.items():
        if name not in self._done:
            self.fields[name].validators.append(validators.MaxValueValidator(value))
            self._done.append(name)

检查部分是因为它有时会多次添加相同的验证器(不知道为什么)

[编辑] 再次检查后,这不能正常工作。显然它总是使用第一个人的max_values来使用表单 - 它实际上没有多大意义。