Reputation: 2166
I am working with Django and its Forms classes.
I have created a Form with a single forms.IntegerField
and I want to define its min_value
parameter dynamically:
class BiddingForm(forms.Form):
bidding_form = forms.IntegerField(min_value=1, help_text="€", label="Bid")
Right now, it is statically set to 1
. I have tried to overwrite the __init__()
function and pass in a min_value
there. But since bidding_form
is a class variable, I cannot use the resulting instance variable min_value
on it:
class BiddingForm(forms.Form):
min_value = 1
def __init__(self, min_value):
super().__init__()
self.min_value = min_value
bidding_form = forms.IntegerField(min_value=min_value, help_text="€", label="Bid")
As of my understanding, above class creates an instance variable min_value
inside of __init__()
which just shadows the class variable min_value
and it ultimately results in min_value
being 1
in the bidding_form
's declaration.
Since I have little understanding of Python and Django, I have not yet found a solution to this.
So, how can I dynamically define forms.IntegerField
's min_value
parameter?
Upvotes: 1
Views: 583
Reputation: 476544
You override the min_value
of the field:
from django.core import validators MinValueValidator
class BiddingForm(forms.Form):
bidding_form = forms.IntegerField(help_text='€', label='Bid')
def __init__(self, *args, min_value=None, **kwargs):
super().__init__(*args, **kwargs)
bidding_form = self.fields['bidding_form']
bidding_form.min_value = min_value
if min_value is not None:
bidding_form.validators.append(MinValueValidator(min_value))
bidding_form.widget.attrs['min'] = min_value
Upvotes: 2
Reputation: 1
Correct way is:
class BidForm(forms.Form):
bid = forms.IntegerField()
def __init__(self, min_bid_value=0, *args, **kwargs):
super(BidForm, self).__init__(*args, **kwargs)
self.fields['bid'].widget.attrs['min'] = min_bid_value
You can call it like :
BidForm(min_bid_value=145)
and form won't let user enter number less than 145.
Upvotes: 0
Reputation: 1
i dont think so but you can do check the length of the specified field before you check if form.is_valid():
. like: if len(form.cleaned_data['field']) < min:
Upvotes: -1