开发者

Django forms integerField set max_value on runtime

I've got a form like this:

class SomeForm(forms.Form):
 first = forms.IntegerField(max_value= DontWantToSetYet)
 second = forms.IntegerField(max_value= DontWantToSetYet)
 third = forms.Integer开发者_开发知识库Field(max_value= DontWantToSetYet)

How can I set the max_values at runtime? I.E

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


you can set the max values on fields in the __init__ method, as shown here

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)

edit:

self.fields['first'].max_value = max_values['first']

didn't worked when I tried, redefining the field definition like this works

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


After reading django source, I came up with something like this:

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)

The checking part is because it would sometimes add the same validator several times (No idea why)

[edit] After checking again, this isn't working as it should. Apparently it always uses the max_values of the first person to use the form - it doesn't make much sense really.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜