Friday, August 6, 2010

CheckBoxInput widget: check_test

Having difficulty getting the check_test to work. Can't find any
examples out there that help. I'll probably have to give a little
background. I simplified where able to...

class Cat:
name = CharField

class Category:
name = ForeignKey(Cat)
weight = DecimalField
item = ForeignKey('Item')

class Item:
name = CharField

Basically Cat is a model of all categories and Category is a model of
which Cat's are assigned to an item. I did it this way because I want
to have a "master list" of categories, then have the mapping done in
other models.

So now I want to build a form at run-time.

def get_form(item):
fields = dict()
cat_choices = [(c.id, c.name) for c in Cat.objects.all()]
for c in cat_choices:
id, name = c
checked = bool(item.categoty_set.filter(pk=id).count())

fields['item_cat_%d' % id] = forms.ChoiceField(
label = name,
required = False,
choices = cat_choices,
widget = forms.CheckboxInput(
attrs={'value': checked},
check_test = lambda a: a == checked
)
)
return type('CatSelectForm', (forms.BaseForm,), {'base_fields':
fields})

So how can I get the correct checkboxes checked at runtime when the
template is rendered?

Thx.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment