-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathfields.py
More file actions
62 lines (44 loc) · 1.82 KB
/
Copy pathfields.py
File metadata and controls
62 lines (44 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from itertools import takewhile
from django import forms
from django_filters.fields import RangeField
from ESSArch_Core.api.forms.widgets import MultipleTextWidget
class MultipleTextField(forms.Field):
widget = MultipleTextWidget
class CharSuffixRangeField(RangeField):
def __init__(self, fields=None, *args, **kwargs):
if fields is None:
fields = (
forms.CharField(),
forms.CharField())
super().__init__(fields, *args, **kwargs)
@staticmethod
def _get_suffix(value):
suffix = ''.join(list(takewhile(str.isdigit, value[::-1])))[::-1]
pos = len(value) - len(suffix)
return suffix, pos
def clean(self, value):
from django.core.exceptions import ValidationError
value = super().clean(value)
if value is None:
return None
start = value.start
stop = value.stop
if start and stop:
if len(start) != len(stop):
raise ValidationError('min and max must be of same length')
if start != '' and not start[-1].isdigit():
raise ValidationError('value must end with a number')
if stop != '' and not stop[-1].isdigit():
raise ValidationError('value must end with a number')
start_suffix, start_suffix_pos = self._get_suffix(start)
stop_suffix, stop_suffix_pos = self._get_suffix(stop)
start_prefix = start[:start_suffix_pos]
stop_prefix = stop[:stop_suffix_pos]
if (start and stop) and \
(start_suffix_pos != stop_suffix_pos or
start_prefix != stop_prefix):
raise ValidationError('Format of min and max does not match')
return (
(start, start_suffix, start_suffix_pos),
(stop, stop_suffix, stop_suffix_pos),
)