I've got a form with a multi checkbox that contains static choices.
Using the forms.MultipleChoiceField with the CheckboxSelectMultiple
widget worked fine for display. However, when displaying an edit form,
the checkboxes did not hold state (all items were unchecked). To
handle this I created a custom widget based on CheckboxSelectMultiple
with the following:
class CustomCheckboxSelectMultiple(SelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<ul>']
# Normalize to strings
if (isinstance(value, basestring)):
value = value.replace('{','')
value = value.replace('}','')
value = value.replace('"','')
value = value.split(',')
str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in
enumerate(chain(self.choices, choices)):
# If an ID attribute was given, add a numeric index as a
suffix,
# so that the checkboxes don't all have the same ID
attribute.
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' %
(attrs['id'], i))
label_for = u' for="%s"' % final_attrs['id']
else:
label_for = ''
cb = CheckboxInput(final_attrs, check_test=lambda value:
value in str_values)
option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value)
option_label =
conditional_escape(force_unicode(option_label))
output.append(u'<li><label%s>%s %s</label></li>' %
(label_for, rendered_cb, option_label))
output.append(u'</ul>')
return mark_safe(u'\n'.join(output))
def id_for_label(self, id_):
# See the comment for RadioSelect.id_for_label()
if id_:
id_ += '_0'
return id_
id_for_label = classmethod(id_for_label)
--------------------------------------------------------------------------------------
My customizations are:
if (isinstance(value, basestring)):
value = value.replace('{','')
value = value.replace('}','')
value = value.replace('"','')
value = value.split(',')
--------------------------------------------------------------------------------------
Is there a better way to do this in django?
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.