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

Flask表单提交报错:TypeError: object of type 'int' has no len()

报错原因分析
  • price字段验证规则错误:你在表单定义中为IntegerField类型的price字段添加了Length验证器,Length仅适用于字符串类型的字段校验,整数类型不存在len()方法,表单验证时会直接触发类型错误。
  • organizer字段类型不匹配:organizer字段定义为StringField且添加了Length验证,但路由中给该字段赋值的current_user.id是整数类型,验证时同样会尝试调用整数的len()方法触发报错。
  • 分类字段赋值隐含问题:QuerySelectField返回的formupload.type.data是Choice模型对象,而Event表的type字段是存储分类id的整数字段,直接赋值后续也会触发类型错误。
解决方法
  1. 修正price字段验证规则,将Length替换为数字范围验证器NumberRange,修改form.py对应代码:
# 先导入验证器
from wtforms.validators import NumberRange

# 替换原price字段定义
price = IntegerField(label='Price:',validators=[DataRequired(), NumberRange(min=1, max=9999999999)])
  1. 修正organizer字段的类型/赋值逻辑,二选一即可:
    • 方案一:将organizer字段改为IntegerField,删除Length验证,适配用户id的整数类型:
    organizer = IntegerField(label='Name:', validators=[DataRequired()], render_kw={'readonly': True})
    
    • 方案二:保留StringField定义,赋值时将用户id转为字符串:
    # routes.py中修改赋值代码
    formupload.organizer.data = str(eventowner)
    
  2. 修正分类字段的赋值逻辑,取Choice对象的id存入Event表,修改routes.py中Event实例化的代码:
event = Event(title=formupload.title.data,
           type=formupload.type.data.id,
           description=formupload.description.data,
           price=formupload.price.data,
           location=formupload.address.data,
           image_file=photos.save(formupload.file.data,
                                  name=str(session.get('id')) + '.jpg',))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:36:06