I'm using a ModelForm class to generate a bunch of checkboxes for a ManyToManyField but I've run into one problem: while the default behaviour automatically checks the appropriate boxes (when I'm editing an object), I can't figure out how to get that information in my own custom templatetag.
Here's what I've got in my model:
...
from django.forms import CheckboxSelectMultiple, ModelMultipleChoiceField
interests = ModelMultipleChoiceField(widget=CheckboxSelectMultiple(), queryset=Interest.objects.all(), required=False)
...
And here's my templatetag:
@register.filter
def alignboxes(boxes, cls):
"""
Details on how this works can be found here:
http://docs.djangoproject.com/en/1.1/howto/custom-template-tags/
"""
r = ""
i = 0
for box in boxes.field.choices.queryset:
r += "<label for=\"id_%s_%d\" class=\"%s\"><input type=\"checkbox\" name=\"%s\" value=\"%s\" id=\"id_%s_%d\" /> %s</label>\n" % (
boxes.name,
i,
cls,
boxes.name,
box.id,
boxes.name,
i,
box.name
)
i = i + 1
return mark_safe(r)
The thing is, I'm only doing this so I can wrap some simpler markup around these boxes, so if someone knows how to make that happen in an easier way, I'm all ears. I'd be happy with knowing a way to access whether or not a box should be checked though.