Debian Codegraph @

sortedm2m/forms.py

raw symbols SCIP
1 from itertools import chain
2
3 from django import forms
4 from django.template.loader import render_to_string
5 from django.utils.encoding import force_str
6 from django.utils.html import conditional_escape
7 from django.utils.safestring import mark_safe
8
9
10 class SortedCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
11 class Media:
12 js = (
13 'admin/js/jquery.init.js',
14 'sortedm2m/widget.js',
15 'sortedm2m/jquery-ui.js',
16 )
17 css = {'screen': (
18 'sortedm2m/widget.css',
19 )}
20
21 def build_attrs(self, attrs=None, **kwargs): # pylint: disable=arguments-differ
22 attrs = dict(attrs or {}, **kwargs)
23 attrs = super().build_attrs(attrs)
24 classes = attrs.setdefault('class', '').split()
25 classes.append('sortedm2m')
26 attrs['class'] = ' '.join(classes)
27 return attrs
28
29 def render(self, name, value, attrs=None, choices=(), renderer=None): # pylint: disable=arguments-differ
30 if value is None:
31 value = []
32 has_id = attrs and 'id' in attrs
33 final_attrs = self.build_attrs(attrs, name=name)
34
35 # Normalize to strings
36 str_values = [force_str(v) for v in value]
37
38 selected = []
39 unselected = []
40
41 for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
42 # If an ID attribute was given, add a numeric index as a suffix,
43 # so that the checkboxes don't all have the same ID attribute.
44 if has_id:
45 final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
46 label_for = ' for="%s"' % conditional_escape(final_attrs['id'])
47 else:
48 label_for = ''
49
50 cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
51 option_value = force_str(option_value)
52 rendered_cb = cb.render(name, option_value)
53 option_label = conditional_escape(force_str(option_label))
54 item = {
55 'label_for': label_for,
56 'rendered_cb': rendered_cb,
57 'option_label': option_label,
58 'option_value': option_value
59 }
60 if option_value in str_values:
61 selected.append(item)
62 else:
63 unselected.append(item)
64
65 # Reorder `selected` array according str_values which is a set of `option_value`s in the
66 # order they should be shown on screen
67 ordered = []
68 for s in str_values:
69 for select in selected:
70 if s == select['option_value']:
71 ordered.append(select)
72 selected = ordered
73
74 html = render_to_string(
75 'sortedm2m/sorted_checkbox_select_multiple_widget.html',
76 {'selected': selected, 'unselected': unselected})
77 return mark_safe(html)
78
79 def value_from_datadict(self, data, files, name):
80 value = data.get(name, None)
81 if isinstance(value, (str,)):
82 return [v for v in value.split(',') if v]
83 return value
84
85
86 class SortedMultipleChoiceField(forms.ModelMultipleChoiceField):
87 widget = SortedCheckboxSelectMultiple
88
89 def clean(self, value):
90 queryset = super().clean(value)
91 if value is None or not hasattr(queryset, '__iter__'):
92 return queryset
93 key = self.to_field_name or 'pk'
94 objects = dict((force_str(getattr(o, key)), o) for o in queryset)
95 return [objects[force_str(val)] for val in value]
96
97 def has_changed(self, initial, data):
98 if initial is None:
99 initial = []
100 if data is None:
101 data = []
102 if len(initial) != len(data):
103 return True
104 initial_set = [force_str(value) for value in self.prepare_value(initial)]
105 data_set = [force_str(value) for value in data]
106 return data_set != initial_set