generic_fields.py
6.97 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
from django import forms
from django.db.models import Q
# TODO: import particular classes?
import crispy_forms.bootstrap as bootstrap
import crispy_forms.layout as layout
from .query_managers import (
SingleValueQueryManager,
MultiValueQueryManager,
RangesQueryManager,
SingleRegexQueryManager,
RegexQueryManager,
ComboQueryManager
)
class LayoutField(object):
def layout(self, x, **kwargs):
return layout.Field(x, **kwargs)
class CheckboxesLayoutField(object):
def layout(self, x, **kwargs):
if self.checkboxes:
return bootstrap.InlineCheckboxes(x, **kwargs)
else:
return layout.Field(x, **kwargs)
class RadiosLayoutField(object):
def layout(self, x, **kwargs):
return bootstrap.InlineRadios(x, **kwargs)
class SelectLayoutField(object):
def layout(self, x, **kwargs):
return layout.Field(x, css_class='custom-select', **kwargs)
# ==============================================================================
#TODO move implementation common for RangesFilter and RegexFilter to an abstract ExpressionFilter?
class RangeFilter(forms.CharField, LayoutField):
def __init__(self, label, lookup, initial='', empty_value='', **kwargs):
super().__init__(label=label, required=False, initial=initial, empty_value=empty_value, **kwargs)
self.query_manager = RangesQueryManager(lookup)
# can’t use static default_validators since the query manager is a class field
def validate(self, value):
self.query_manager.expression_validator(value)
class RegexFilter(forms.CharField, LayoutField):
def __init__(self, label, lookup, additional_operators=False, initial='.*', empty_value='.*', autocomplete=None, **kwargs):
self.css_class = 'regex-autocomplete' if autocomplete else None
self.data_autocomplete = autocomplete if autocomplete else None
super().__init__(label=label, required=False, initial=initial, empty_value=empty_value, **kwargs)
self.query_manager = RegexQueryManager(lookup, additional_operators=additional_operators)
# can’t use static default_validators since validation depends on the
# query_manager instance (allowed operators)
def validate(self, value):
self.query_manager.expression_validator(value)
def layout(self, x, **kwargs):
return layout.Field(x, css_class=self.css_class, data_autocomplete=self.data_autocomplete, **kwargs)
class SingleRegexFilter(forms.CharField, LayoutField):
def __init__(self, label, lookup, initial='.*', empty_value='.*', **kwargs):
super().__init__(label=label, required=False, initial=initial, empty_value=empty_value, **kwargs)
self.query_manager = SingleRegexQueryManager(lookup)
class MultipleChoiceFilter(forms.MultipleChoiceField, CheckboxesLayoutField):
def __init__(self, label, choices, lookup, **kwargs):
super().__init__(
label=label,
choices=choices,
required=False,
**kwargs
)
self.query_manager = MultiValueQueryManager(lookup, default_conjunction=False)
self.checkboxes = True
class ModelMultipleChoiceFilter(forms.ModelMultipleChoiceField, CheckboxesLayoutField):
def __init__(self, label, queryset, key, lookup, human_values={}, checkboxes=True, **kwargs):
super().__init__(
label=label,
queryset=queryset,
required=False,
**kwargs
)
self.query_manager = MultiValueQueryManager(lookup, default_conjunction=False)
self.key = key
self.human_values = human_values
self.checkboxes = checkboxes
def label_from_instance(self, obj):
return self.human_values.get(obj.__dict__[self.key], obj.__dict__[self.key])
class ModelChoiceFilter(forms.ModelChoiceField, SelectLayoutField):
def __init__(self, label, queryset, key, lookup, human_values={}, **kwargs):
super().__init__(
label=label,
queryset=queryset,
required=False,
**kwargs
)
self.query_manager = SingleValueQueryManager(lookup)
# str object or callable
self.key = key
self.human_values = human_values
def label_from_instance(self, obj):
if type(self.key) == str:
return self.human_values.get(obj.__dict__[self.key], obj.__dict__[self.key])
else:
return self.key(obj)
'''
# MultiValueField is an abstract class, must be subclassed and implement compress
class ComboFilter(forms.MultiValueField, LayoutField):
# MultiWidget is an abstract class, must be subclassed and implement decompress
class ComboWidget(forms.widgets.MultiWidget):
def decompress(self, value):
return value if value else [None for i in range(len(self.widgets))]
def layout(self, x, **kwargs):
attrs = []
for i, field in enumerate(self.fields):
cls = ['col-sm-3']
if i < len(self.fields) - 1:
cls.append('mr-4')
if type(field) == SwitchField:
cls += ['custom-switch']
elif type(field) == ModelChoiceFilter:
cls.append('custom-select')
elif type(field) == SingleRegexFilter:
cls.append('form-control')
attrs.append({'class' : ' '.join(cls)})
return layout.MultiWidgetField(x, attrs=attrs, **kwargs)
def __init__(self, label, inner_class, outer_lookup, fields, negation_field=False, **kwargs):
neg_fields = [SwitchField('!')] if negation_field else []
all_fields = neg_fields + fields
super().__init__(
label=label,
fields=all_fields,
widget=self.ComboWidget(widgets=[field.widget for field in all_fields]),
required=False,
**kwargs
)
self.query_fields = fields
self.query_manager = ComboQueryManager(inner_class, outer_lookup, [f.query_manager for f in fields], negation_field)
def compress(self, data_list):
return data_list
'''
class OperatorField(forms.ChoiceField, RadiosLayoutField):
def __init__(self):
super().__init__(
label=' ',
choices=((False, 'lub'), (True, 'i')),
initial=False,
required=False,
)
def to_python(self, value):
if value in ('1', 'true', 'True', True):
return True
if value in ('0', 'false', 'False', False):
return False
return None
class SwitchField(forms.BooleanField, LayoutField):
def __init__(self, label, css_class=None):
super().__init__(label=label, required=False)
self.css_class = css_class
def layout(self, x, **kwargs):
wrapper_class = 'custom-switch float-right font-weight-bold'
if self.css_class:
wrapper_class += ' ' + self.css_class
return layout.Field(x, wrapper_class=wrapper_class, **kwargs)