Skip to content

Instantly share code, notes, and snippets.

@yuvadm
Last active June 29, 2017 11:52
Show Gist options
  • Save yuvadm/859f96e263924588675efb5dc6d557f6 to your computer and use it in GitHub Desktop.
Save yuvadm/859f96e263924588675efb5dc6d557f6 to your computer and use it in GitHub Desktop.
Select2 Django admin widget for ArrayFields
class ArrayTagWidget(Select2TagWidget):
def build_attrs(self, *args, **kwargs):
self.attrs.setdefault('data-token-separators', [])
self.attrs.setdefault('data-width', '500px')
self.attrs.setdefault('data-tags', 'true')
return super().build_attrs(*args, **kwargs)
def value_from_datadict(self, data, files, name):
values = super().value_from_datadict(data, files, name)
return ','.join([x.replace(',', '|') for x in values])
def optgroups(self, name, value, attrs=None):
values = [x.replace('|', ',') for x in value[0].split(',')] if value[0] else []
selected = {*values}
subgroup = [self.create_option(name, v, v, selected, i) for i, v in enumerate(values)]
return [(None, subgroup, 0)]
@yuvadm
Copy link
Author

yuvadm commented Jun 29, 2017

Updated to support Django 1.11 after some breaking changes in the widget rendering API

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment