On Aug 6, 7:13 pm, lingrlongr <keith.ebe...@gmail.com> wrote: > 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.
The closure isn't acting the way you think. Each lambda is bound to the same `checked` variable, whose value is changed each time through the loop - so when it is actually evaluated, it has the value of the last time through. One way of fixing this is to use a nested function, rather than a lambda, with a default value: for c in cat_choices: ... checked = bool(item.category_set.filter(pk=id).count()) def is_checked(a, checked=checked): return a == checked .... widget = forms.CheckboxInput( attrs={'value': checked}, check_test = is_checked ) This creates a new function each time, with the default parameter set to the value of `checked` at the time it was defined. -- DR. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.