john_science
john_science

Reputation: 6541

Exclusive Limits on Form Fields

I have the following field in a Django form:

area = forms.FloatField(required=False, min_value=0, max_value=100)

How do I make the minimum limit exclusive and the maximum limit inclusive?

The Django page on this form doesn't mention anything about exclusivity versus inclusivity. And looking at the source code makes me think this isn't directly built into Django. Am I right? If so, how could I work around this?

Upvotes: 0

Views: 263

Answers (2)

Fiver
Fiver

Reputation: 10167

I would write a custom clean_field method in your form like so:

def clean_area(self):
    data = self.cleaned_data['area']
    if (data > 0 and data <= 100):
        return ValidationError("Some custom message alerting the user!")
    return data

The method just has to return the value you want, see the Django docs

Then, just re-define your field as:

area = forms.FloatField(required=False)  # see additional clean field method

Upvotes: 2

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

Write a custom validator to do it. They're not complex, and the existing MinValueValidator and MaxValueValidator in django.core.validators will give you a good starting point.

https://docs.djangoproject.com/en/dev/ref/validators/#writing-validators

class ExclusiveMinValueValidator(BaseValidator):
    compare = lambda self, a, b: a <= b
    message = _(u'Ensure this value is greater than %(limit_value)s.')
    code = 'min_value'

You could also write a custom clean method for the field.

Upvotes: 4

Related Questions