Django:动态表单无法正确处理布尔输入

问题描述 投票:0回答:1

这是我动态构建的一个小表单:

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})")

这就是我的使用方式:

            form = AddonForm(ItemAddonTemplate.objects.filter(item=item_template_id), request.POST)
            if form.is_valid():
                addons = form.cleaned_data

这是请求。POST:

<QueryDict: {'csrfmiddlewaretoken': ['cJS1fhGY3WqIflynGbZIh9TiRj8F9HjgoLOUL6TwWY4j4cotALGHpFDyQwjLiLMW'], '3': ['on'], '32': ['on']}>

但是当我打印插件时我看到这个:

{'3': False, '30': False, '31': False, '32': False, '33': False, '34': False}

3 和 32 应该是 True。

这是 Django 5.1 和 Python 3.12。

django forms
1个回答
0
投票

也许,使用

formsets
来实现更好:

表格.py

class AddonForm(Form):
    on = BooleanField(required=False)

    def __init__(self, addons, *args, **kwargs):
        """
        Use addons qs(as list) to add and set
        properties to the form and form fields
        """
        super().__init__(*args, **kwargs)
        addon = addons.pop(0)
        self.label = f"{addon} (x{addon.price_multiplier})"
        self.identifier = addon.id
        self.fields["on"].label = self.label

    def clean(self):
        """
        Change cleaned_data representation
        substituting the field name for addon.id
        """
        cleaned_data = super().clean()
        cleaned_data[f"{self.identifier}"] = cleaned_data.pop("on")
        return cleaned_data

views.py

def item_addons(request, item_template_id):
    addons = ItemAddonTemplate.objects.filter(item=item_template_id)

    AlternativeFormSet = formset_factory(AddonForm, extra=len(addons))
    formset = AlternativeFormSet(form_kwargs={"addons": list(addons)})

    if request.method == "POST":
        formset = AlternativeFormSet(request.POST, form_kwargs={"addons": list(addons)})
        if formset.is_valid():
            for form in formset:
                if form.cleaned_data:
                    print(form.cleaned_data)

    return render(request, "item_addons.html", {"formset": formset})

哪个“返回”:

{'3': True}
{'32': True}
© www.soinside.com 2019 - 2024. All rights reserved.