combo/combo/utils/forms.py

69 lines
2.7 KiB
Python

# combo - content management system
# Copyright (C) 2014-2018 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django import forms
from django.utils.datastructures import MultiValueDict
from django.utils.safestring import mark_safe
class MultiSortWidget(forms.SelectMultiple):
def __init__(self, *args, **kwargs):
if 'with_checkboxes' in kwargs:
self.with_checkboxes = kwargs.pop('with_checkboxes')
else:
self.with_checkboxes = False
super(MultiSortWidget, self).__init__(*args, **kwargs)
def render(self, name, value, attrs=None, choices=()):
# reorder choices to get them in the current value order
self_choices = self.choices[:]
choices_dict = dict(self_choices)
if value:
for option in reversed(value.get('data')):
if option not in choices_dict:
continue
option_tuple = (option, choices_dict[option])
self.choices.remove(option_tuple)
self.choices.insert(0, option_tuple)
# render the <select multiple>
rendered = super(MultiSortWidget, self).render(name, value,
attrs=attrs)
# include it in a <div> that will be turned into an appropriate widget
# in javascript
id_ = 'wid-%s' % name
if self.with_checkboxes:
attrs = 'data-checkboxes="true"'
else:
attrs = ''
return mark_safe('''<div class="multisort" %s id="%s">%s</div>
<script type="text/javascript">multisort($("#%s"));</script>
''' % (attrs, id_, rendered, id_))
def render_options(self, choices, value):
value = value.get('data') or []
return super(MultiSortWidget, self).render_options(choices, value)
def value_from_datadict(self, data, files, name):
if isinstance(data, MultiValueDict):
return {'data': data.getlist(name)}
return data.get(name, None)
def format_value(self, value):
value = value.get('data') or []
return super(MultiSortWidget, self).format_value(value)