array.py 780 B

1234567891011121314151617181920212223242526
  1. from django import forms
  2. from django.contrib.postgres.forms import SimpleArrayField
  3. from django.utils.translation import gettext_lazy as _
  4. from ..utils import parse_numeric_range
  5. __all__ = (
  6. 'NumericArrayField',
  7. )
  8. class NumericArrayField(SimpleArrayField):
  9. def clean(self, value):
  10. if value and not self.to_python(value):
  11. raise forms.ValidationError(
  12. _("Invalid list ({value}). Must be numeric and ranges must be in ascending order.").format(value=value)
  13. )
  14. return super().clean(value)
  15. def to_python(self, value):
  16. if not value:
  17. return []
  18. if isinstance(value, str):
  19. value = ','.join([str(n) for n in parse_numeric_range(value)])
  20. return super().to_python(value)