Created
December 25, 2009 09:06
-
-
Save avostryakov/263569 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MultiTextInputWidget(forms.TextInput): | |
""" | |
A widget that is composed of multiple TextInput widgets. | |
Its render() display multiple TextInput widgets. | |
The ``value`` argument supposes to be a dictionary in json format or string | |
This widget can be used together with MultiTextInputField. | |
""" | |
def __init__(self, attrs=None): | |
super(MultiTextInputWidget, self).__init__(attrs) | |
def render(self, name, value, attrs=None): | |
# value is a dictionary in json format or string | |
final_attrs = self.build_attrs(attrs) | |
id_ = final_attrs.get('id', None) | |
output = [] | |
try: | |
value = json_loads(value) | |
if isinstance(value, dict): | |
for i, key in enumerate(value): | |
if id_: | |
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i)) | |
output.append(u'<label for="%s">%s:</label>%s' % (final_attrs['id'], key, | |
super(MultiTextInputWidget, self).render(name + '_%s' % key, value[key], final_attrs))) | |
else: | |
raise ValueError() | |
except ValueError: | |
final_attrs = dict(final_attrs, id='%s_%s' % (id_, 0)) | |
output.append(super(MultiTextInputWidget, self).render(name, value, final_attrs)) | |
return mark_safe(u''.join(output)) | |
def id_for_label(self, id_): | |
if id_: | |
id_ += '_0' | |
return id_ | |
id_for_label = classmethod(id_for_label) | |
def value_from_datadict(self, data, files, name): | |
""" | |
Combine values of the field from data-dictionary. | |
""" | |
if name in data: | |
value = data.get(name, None) | |
else: | |
value = {} | |
for key in data: | |
if key.startswith(name): | |
n, suffix = key.rsplit('_', 1) | |
value[suffix] = data.get(key, None) | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment