Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.IntegerField(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})
    [...]
like image 200
Robus Avatar asked Dec 28 '22 08:12

Robus


1 Answers

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'])
like image 77
Ashok Avatar answered Jan 15 '23 22:01

Ashok