关于Django出现“__str__ returned non-string (type NoneType)”错误的处理

跟着cls超哥学django,只不过我用的版本是python3.85,Django版本为3.1.2。我总是想用最新的东西,尽管为此付出了不小的代价。噢,还有我是在Deepin20下学习。
仔细检查发现代码没有什么错误,花了我好多时间。不过这好多时间,都是不断测试我的模板语法是否有错。

Error during template rendering
In template /home/zyl07/PycharmProjects/SCRM/sales/templates/sales_html/starter.html, error at line 12

因为,这两行错误信息太容易看到了!前前后后,折腾了一个下午,还是没有解决。没办法,只好静下心来,仔细看了错误提示:

TypeError at /sales/add_customer/
__str__ returned non-string (type NoneType)
Request Method:	GET
Request URL:	http://127.0.0.1:8000/sales/add_customer/
Django Version:	3.1.2
Exception Type:	TypeError
Exception Value:	
__str__ returned non-string (type NoneType)
Exception Location:	/home/zyl07/djs/djs3/lib/python3.8/site-packages/django/forms/models.py, line 1240, in label_from_instance
Python Executable:	/home/zyl07/djs/djs3/bin/python
Python Version:	3.8.5
Python Path:	
['/home/zyl07/PycharmProjects/SCRM',
 '/home/zyl07/PycharmProjects/SCRM',
 '/home/zyl07/pycharm/pycharm-2020.2/plugins/python/helpers/pycharm_display',
 '/usr/local/lib/python38.zip',
 '/usr/local/lib/python3.8',
 '/usr/local/lib/python3.8/lib-dynload',
 '/home/zyl07/djs/djs3/lib/python3.8/site-packages',
 '/home/zyl07/pycharm/pycharm-2020.2/plugins/python/helpers/pycharm_matplotlib_backend']
Server time:	Mon, 19 Oct 2020 19:57:22 +0800

我发现异常出现在这个位置:
Exception Location: /home/zyl07/djs/djs3/lib/python3.8/site-packages/django/forms/models.py, line 1240, in label_from_instance
打开源文件:

    def label_from_instance(self, obj):
        """
        Convert objects into strings and generate the labels for the choices
        presented by this object. Subclasses can override this method to
        customize the display of the choices.
        """
        return str(obj)

这只不过是某一个类的一个方法。要往前追代码太困难了,再说,我也不定看得懂。于是用了一个笨办法。

    def label_from_instance(self, obj):
        """
        Convert objects into strings and generate the labels for the choices
        presented by this object. Subclasses can override this method to
        customize the display of the choices.
        """
        print(type(obj))
      # 下面这一句主要是为了显示明显!
        print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
        return str(obj)

第一次修改Pycharm还提示,你是否真得要修改。果断修改,反正我还能改回来。重启服务器,刷新页面。天哪,看出现了什么 ?

<class 'sales.models.Customer'>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
<class 'sales.models.Customer'>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
<class 'sales.models.Customer'>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
<class 'sales.models.Customer'>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
<class 'sales.models.Customer'>

出现了一片这个玩意儿。这样,我就知道目标在哪儿了。其实问题就出在我的Customer类中有一个name字段,是可以为空的,也就是说可以不填数据。
但是下面的__str__方法中,我却将这个字段返回。所以,就造成了returned non-string (type NoneType)这样的错误。本为应该返回字符串,却返回了一个None类型。
找到了问题,解决办法就有了,要不你返回其他字段,不可以为空的字段;要不加上个判断,如果为None时,返回一个特定的字符串就可以了。

    def __str__(self):
        if self.name:
            return self.name
        else:
            return "未留姓名"
原文地址:https://www.cnblogs.com/xiaolee-tech/p/13842804.html