Login

IntegerRangeField

Author:
moemen
Posted:
January 1, 2014
Language:
Python
Version:
Not specified
Tags:
models fields IntegerField
Score:
0 (after 0 ratings)

Django models IntegerField that get max_value and min_value in it's constructor and validate on it.

It's initialize the formfield with min_value and max_value, too.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models


class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        validators = []
        if isinstance(max_value, int):
            validators.append(MaxValueValidator(max_value))
        if isinstance(min_value, int):
            validators.append(MinValueValidator(min_value))
        models.IntegerField.__init__(
            self,
            verbose_name,
            name,
            validators=validators,
            **kwargs
        )

    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        return super(IntegerRangeField, self).formfield(**defaults)

More like this

  1. OrderField by zenx 5 years, 6 months ago
  2. TinyIntegerField by Lacour 3 years, 11 months ago
  3. keeping Model and Field History (everywhere) by buriy 6 years, 10 months ago
  4. Fixed-point Decimal model field with integer storage by lanzz 1 year, 4 months ago
  5. BigIntegerField and BigAutoField by fnl 6 years, 7 months ago

Comments

Please login first before commenting.