Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

python - How can I dynamically define forms.IntegerField's min_value parameter?

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?

question from:https://stackoverflow.com/questions/65645201/how-can-i-dynamically-define-forms-integerfields-min-value-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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__(self, *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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...