9627 numeric range field

This commit is contained in:
Arthur Hanson 2024-06-20 13:59:46 -07:00
parent 2f2945b825
commit 8e67c548af
2 changed files with 31 additions and 26 deletions

View File

@ -1,11 +1,13 @@
from django import forms
from django.contrib.postgres.forms import SimpleArrayField
from django.db.backends.postgresql.psycopg_any import NumericRange
from django.utils.translation import gettext_lazy as _
from ..utils import parse_numeric_range
__all__ = (
'NumericArrayField',
'NumericRangeArrayField',
)
@ -24,3 +26,32 @@ class NumericArrayField(SimpleArrayField):
if isinstance(value, str):
value = ','.join([str(n) for n in parse_numeric_range(value)])
return super().to_python(value)
class NumericRangeArrayField(forms.CharField):
"""
A field which allows for array of numeric ranges:
Example: 1-5,7-20,30-50
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.help_text:
self.help_text = _(
"Specify one or more numeric ranges separated by commas "
"Example: <code>1-5,20-30</code>"
)
def prepare_value(self, value):
range_str = ','.join([f"{val.lower}-{val.upper}" for val in value])
return range_str
def to_python(self, value):
if not value:
return ''
ranges = value.split(",")
values = []
for dash_range in value.split(','):
begin, end = dash_range.split('-')
values.append(NumericRange(begin, end))
return values

View File

@ -1,7 +1,6 @@
import re
from django import forms
from django.db.backends.postgresql.psycopg_any import NumericRange
from django.utils.translation import gettext_lazy as _
from utilities.forms.constants import *
@ -10,7 +9,6 @@ from utilities.forms.utils import expand_alphanumeric_pattern, expand_ipaddress_
__all__ = (
'ExpandableIPAddressField',
'ExpandableNameField',
'NumericRangeArrayField',
)
@ -55,27 +53,3 @@ class ExpandableIPAddressField(forms.CharField):
elif ':' in value and re.search(IP6_EXPANSION_PATTERN, value):
return list(expand_ipaddress_pattern(value, 6))
return [value]
class NumericRangeArrayField(forms.CharField):
"""
A field which allows for array of numeric ranges:
Example: 1-5,7-20,30-50
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.help_text:
self.help_text = _(
"Specify one or more numeric ranges separated by commas "
"Example: <code>1-5,20-30</code>"
)
def to_python(self, value):
if not value:
return ''
ranges = split(value, ",")
numeric_ranges = []
for range in ranges:
numeric_ranges.append(NumericRange(range[0], range[1]))
return [numeric_ranges]