- Author:
- moemen
- Posted:
- January 1, 2014
- Language:
- Python
- Version:
- Not specified
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.