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

Django模型ArrayField提交表单提示数组项验证失败如何解决

问题根因

SelectMultiple控件提交的多选值默认是字符串类型列表,而模型中ArrayField嵌套的是IntegerField,要求存储整数类型子项。表单校验时拿到的字符串值无法通过整数类型校验,就会抛出Item 1 in the array did not validate错误。

修复方案

不要仅在Meta.widgets中配置控件,显式在表单中声明TypedMultipleChoiceField类型字段,通过coerce=int参数自动完成提交值的字符串转整数逻辑即可:

from django import forms
from .models import Mymodel

class MymodelForm(forms.ModelForm):
    # 显式定义regione字段,配置类型强转
    regione = forms.TypedMultipleChoiceField(
        choices=REGIONE_CHOICES,
        coerce=int, # 把提交的字符串选项值转为整数
        required=False, # 匹配模型中blank=True的配置,允许留空
        widget=forms.SelectMultiple
    )

    class Meta:
        model = Mymodel
        fields = ['some_fields', 'regione']
        # 移除原Meta.widgets中regione的重复配置即可

注:原模型字段定义中内层IntegerField的default=0和外层ArrayField的default=None存在配置冗余,可根据实际业务需求清理,该冗余不会触发本次校验错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 05:27:21