You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何指定Django MultipleChoiceField的归一化类型?无需子类重写

解决方案:用TypedMultipleChoiceField指定类型转换

不用创建子类或重写原有方法就能搞定——直接替换原来的MultipleChoiceField为Django内置的TypedMultipleChoiceField,通过coerce参数指定类型转换规则即可。

TypedMultipleChoiceField是MultipleChoiceField的扩展,专门针对需要对选中值做类型转换的场景设计,coerce参数接收一个转换函数(比如int),会自动把表单提交的字符串值转换成你需要的类型。

修改后的表单代码如下:

from django import forms
from django.utils.translation import gettext_lazy as _

class MyForm(forms.Form):
    owner = forms.TypedMultipleChoiceField(
        label=_("Owners"),
        required=False,
        widget=forms.SelectMultiple(attrs={"class":"form_multi_select"}),
        coerce=int,  # 核心参数:将字符串转为int类型
    )
    
    def __init__(self, *args, **kwargs):
         self.choice_options = kwargs.pop("choice_options")
         super().__init__(*args, **kwargs)
         owners = self.choice_options.get("owner")
         self.fields["owner"].choices = owners.ungrouped() if owners else []

这样处理后,表单验证通过时,cleaned_data['owner']中的每个值都会是int类型,和你传入的选项格式完全匹配。

内容的提问来源于stack exchange,提问作者Iustinian Olaru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 08:50:39