From: Matthijs Kooijman Date: Sun, 1 Feb 2009 17:31:37 +0000 (+0100) Subject: Add a DropDownMultiple form widget. X-Git-Url: https://git.stderr.nl/gitweb?a=commitdiff_plain;ds=inline;h=053fc78de59d8f55c276d3b1c89ecc7997a64985;p=matthijs%2Fprojects%2Fxerxes.git Add a DropDownMultiple form widget. This code is taken literally from http://www.djangosnippets.org/snippets/747/, only "newforms" was changed to "forms". --- diff --git a/tools/widgets/__init__.py b/tools/widgets/__init__.py new file mode 100644 index 0000000..1608809 --- /dev/null +++ b/tools/widgets/__init__.py @@ -0,0 +1 @@ +from dropdownmultiple import DropDownMultiple diff --git a/tools/widgets/dropdownmultiple.py b/tools/widgets/dropdownmultiple.py new file mode 100644 index 0000000..37e17e4 --- /dev/null +++ b/tools/widgets/dropdownmultiple.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +from django.forms import widgets +from django.utils.safestring import mark_safe +from django.utils.datastructures import MultiValueDict +from django.newforms.util import flatatt + +TPL_OPTION = """""" + +TPL_SELECT = """ + +""" + +TPL_SCRIPT = """ + +""" + +TPL_FULL = """ + +%(values)s +%(script)s + +""" + +class DropDownMultiple(widgets.Widget): + choices = None + + def __init__(self, attrs=None, choices=()): + self.choices = choices + + super(DropDownMultiple, self).__init__(attrs) + + def render(self, name, value, attrs=None, choices=()): + if value is None: value = [] + final_attrs = self.build_attrs(attrs, name=name) + + # Pop id + id = final_attrs['id'] + del final_attrs['id'] + + # Insert blank value + choices = [('','---')] + list(self.choices) + + # Build values + items = [] + for val in value: + opts = "\n".join([TPL_OPTION %{'value': k, 'desc': v, 'selected': val == k and 'selected="selected"' or ''} for k, v in choices]) + + items.append(TPL_SELECT %{'attrs': flatatt(final_attrs), 'opts': opts}) + + # Build blank value + opts = "\n".join([TPL_OPTION %{'value': k, 'desc': v, 'selected': ''} for k, v in choices]) + items.append(TPL_SELECT %{'attrs': flatatt(final_attrs), 'opts': opts}) + + script = TPL_SCRIPT %{'id': id} + output = TPL_FULL %{'id': id, 'values': '\n'.join(items), 'script': script} + + return mark_safe(output) + + def value_from_datadict(self, data, files, name): + if isinstance(data, MultiValueDict): + return [i for i in data.getlist(name) if i] + + return data.get(name, None)