SHARE
TWEET

Untitled

a guest Mar 24th, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from typing import Dict, Optional, Any
  2.  
  3. from django.db import models
  4. from django.core.validators import MinValueValidator, MaxValueValidator
  5. from django import forms
  6.  
  7.  
  8. class BaseBoundedField(models.Field):
  9.     def __init__(
  10.             self,
  11.             min_value: float = float('-infinity'),
  12.             max_value: float = float('infinity'),
  13.             step: Optional[float] = None,
  14.             *args: Any, **kwargs: Any):
  15.         self.max_value = max_value
  16.         self.min_value = min_value
  17.         self.step = step
  18.         kwargs['validators'] = list(kwargs.get('validators', [])) + [
  19.             MinValueValidator(self.min_value),
  20.             MaxValueValidator(self.max_value)]
  21.         super().__init__(*args, **kwargs)
  22.  
  23.     def _get_widget_attrs(self) -> Dict[str, str]:
  24.         attrs = {}
  25.         if self.max_value < float('infinity'):
  26.             attrs['max'] = str(self.max_value)
  27.         if self.min_value > float('-infinity'):
  28.             attrs['min'] = str(self.min_value)
  29.         if self.step is not None:
  30.             attrs['step'] = str(self.step)
  31.         return attrs
  32.  
  33.  
  34. class BoundedFloatField(BaseBoundedField, models.FloatField):
  35.     def formfield(self, **kwargs: Any) -> forms.Field:
  36.         defaults = {
  37.             'widget': forms.NumberInput(attrs=self._get_widget_attrs()),
  38.         }
  39.         defaults.update(kwargs)
  40.         return super().formfield(**defaults)
  41.  
  42.  
  43. class BoundedIntegerField(BaseBoundedField, models.IntegerField):
  44.     def formfield(self, **kwargs: Any) -> forms.Field:
  45.         defaults = {
  46.             'widget': forms.NumberInput(attrs=self._get_widget_attrs()),
  47.         }
  48.         defaults.update(kwargs)
  49.         return super().formfield(**defaults)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top