File tree Expand file tree Collapse file tree 3 files changed +29
-5
lines changed Expand file tree Collapse file tree 3 files changed +29
-5
lines changed Original file line number Diff line number Diff line change @@ -160,9 +160,17 @@ def string_to_ranges(value):
160160 return None
161161 value .replace (' ' , '' ) # Remove whitespace
162162 values = []
163- for dash_range in value .split (',' ):
164- if '-' not in dash_range :
163+ for data in value .split (',' ):
164+ dash_range = data .strip ().split ('-' )
165+ if len (dash_range ) == 1 and str (dash_range [0 ]).isdigit ():
166+ # Single integer value; expand to a range
167+ lower = dash_range [0 ]
168+ upper = dash_range [0 ]
169+ elif len (dash_range ) == 2 and str (dash_range [0 ]).isdigit () and str (dash_range [1 ]).isdigit ():
170+ # The range has two values and both are valid integers
171+ lower = dash_range [0 ]
172+ upper = dash_range [1 ]
173+ else :
165174 return None
166- lower , upper = dash_range .split ('-' )
167175 values .append (NumericRange (int (lower ), int (upper ), bounds = '[]' ))
168176 return values
Original file line number Diff line number Diff line change @@ -32,12 +32,14 @@ def to_python(self, value):
3232class NumericRangeArrayField (forms .CharField ):
3333 """
3434 A field which allows for array of numeric ranges:
35- Example: 1-5,7-20,30-50
35+ Example: 1-5,10,20-30
3636 """
3737 def __init__ (self , * args , help_text = '' , ** kwargs ):
3838 if not help_text :
3939 help_text = mark_safe (
40- _ ("Specify one or more numeric ranges separated by commas. Example: " + "<code>1-5,20-30</code>" )
40+ _ (
41+ "Specify one or more individual numbers or numeric ranges separated by commas. Example: {example}"
42+ ).format (example = "<code>1-5,10,20-30</code>" )
4143 )
4244 super ().__init__ (* args , help_text = help_text , ** kwargs )
4345
Original file line number Diff line number Diff line change @@ -66,3 +66,17 @@ def test_string_to_ranges(self):
6666 NumericRange (100 , 199 , bounds = '[]' ), # 100-199
6767 ]
6868 )
69+
70+ self .assertEqual (
71+ string_to_ranges ('1-2, 5, 10-12' ),
72+ [
73+ NumericRange (1 , 2 , bounds = '[]' ), # 1-2
74+ NumericRange (5 , 5 , bounds = '[]' ), # 5-5
75+ NumericRange (10 , 12 , bounds = '[]' ), # 10-12
76+ ]
77+ )
78+
79+ self .assertEqual (
80+ string_to_ranges ('2-10, a-b' ),
81+ None # Fails to convert
82+ )
You can’t perform that action at this time.
0 commit comments