Django: Dynamic form doesn't correctly handle boolean inputs
This is a small form I have and dynamically construct:
class AddonForm(Form):
def __init__(self, addons, *args, **kwargs):
super().__init__(self, *args, **kwargs)
self.addons = {str(addon.pk): addon for addon in addons}
for pk, addon in self.addons.items():
self.fields[str(pk)] = BooleanField(required=False, label=f"{addon} (x{addon.price_multiplier})")
This is how I use it:
form = AddonForm(ItemAddonTemplate.objects.filter(item=item_template_id), request.POST)
if form.is_valid():
addons = form.cleaned_data
This is the request.POST:
<QueryDict: {'csrfmiddlewaretoken': ['cJS1fhGY3WqIflynGbZIh9TiRj8F9HjgoLOUL6TwWY4j4cotALGHpFDyQwjLiLMW'], '3': ['on'], '32': ['on']}>
but when I print addons I see this:
{'3': False, '30': False, '31': False, '32': False, '33': False, '34': False}
3 and 32 should be True.
This is Django 5.1 and Python 3.12.