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

Django /add_items/页面TypeError:str返回非字符串(NoneType)

排查 TypeError: str returned non-string (type NoneType) 错误

首先,这个错误的直接根源在你的Stock模型的__str__方法里:

def __str__(self):
    return self.item_name

因为你给item_name字段设置了blank=True, null=True,当这条记录的item_name为None时,__str__方法返回了None类型,而Python要求__str__必须返回字符串,所以触发了这个TypeError。

修复方案:

修改Stock模型的__str__方法,确保无论item_name是否为空都返回字符串:

def __str__(self):
    return self.item_name or "Unnamed Item"  # 当item_name为None时返回默认字符串

顺便帮你排查其他潜在问题:

  • 表单里重复的clean_item_name方法:
    你写了两个clean_item_name函数,第二个会覆盖第一个,而且第一个函数里的category变量根本没定义,这会导致隐藏的bug。删掉第一个无效的clean_item_name,只保留正确的那个:

    # 删掉下面这段无效的代码
    # def clean_item_name(self):
    #     item_name = self.cleaned_data.get('item_name')
    #     if not category:
    #         raise forms.ValidationError('This field is required')
    #     for instance in Stock.objects.all():
    #         if instance.category == item_name:
    #             raise forms.ValidationError(str(item_name) + ' is already created')
    #     return category
    
  • 视图里多余的messages.success调用:
    你连续调用了两次messages.success,而且把返回值赋值给z,其实messages.success返回None,这段代码没有实际意义,建议删掉多余的那行:

    # 删掉下面这两行
    # z=messages.success(request, 'Successfull')
    # print(z)
    
  • 模型字段的默认值问题:
    quantity字段的默认值设为字符串'0',但它是IntegerField,应该改为数字0:

    quantity = models.IntegerField(default=0, blank=True, null=True)
    

这些调整不仅能解决当前的TypeError,还能避免后续出现其他隐藏bug。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:22:54