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

Django使用TextChoices时表单验证报错:1不是有效选项

问题原因与解决方案

问题根源

你遇到的验证错误,核心原因是**TextChoices的选项值类型和模型字段类型不匹配**:

  • TextChoices定义的选项值默认是字符串类型(比如'1')
  • 但你的sex字段是PositiveSmallIntegerField(整数类型)
    表单提交时,传递的字符串值无法匹配字段要求的整数类型,因此触发"Select a valid choice. 1 is not one of the available choices"错误。

解决方案

有两种可行的修改方式,推荐优先选择模型层面的修改:

方式1:修改模型,将TextChoices替换为IntegerChoices

IntegerChoices的选项值是整数类型,和PositiveSmallIntegerField完全匹配,无需额外处理表单:

from django.db import models

class Cat(models.Model):
    # 把TextChoices改成IntegerChoices
    class Sex(models.IntegerChoices):
        MALE = 1, '公猫'
        FEMALE = 2, '母猫'
    
    sex = models.PositiveSmallIntegerField(choices=Sex.choices)

方式2:修改表单,强制转换提交值类型

如果不想改动模型,可以在CatForm中重写sex字段,通过coerce参数将提交的字符串值转为整数:

from django import forms
from .models import Cat

class CatForm(forms.ModelForm):
    sex = forms.TypedChoiceField(
        choices=Cat.Sex.choices,
        coerce=int,  # 强制把提交的字符串转为整数
        widget=forms.Select
    )
    
    class Meta:
        model = Cat
        fields = ['sex', ...]  # 其他字段按需添加

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:32:34