管理员错误:__str__ 返回非字符串(类型 NoneType)

Error in admin: __str__ returned non-string (type NoneType)

管理员 return 在尝试将实例添加到我的模型之一时出现此错误。模型本身有一个正确的 str() 方法并且不包含任何实例。还尝试用静态方法替换 str() 方法或将其完全删除。运气不好。

该错误似乎表明管理员的历史记录部分出了问题。 Stacktrace 指向第 33 行。

Error during template rendering

In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33
__str__ returned non-string (type NoneType)
23  {% endblock %}
24  {% endif %}
25  
26  {% block content %}<div id="content-main">
27  {% block object-tools %}
28  {% if change %}{% if not is_popup %}
29    <ul class="object-tools">
30      {% block object-tools-items %}
31      <li>
32          {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %}
33          <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a>
34      </li>
35      {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %}
36      {% endblock %}
37    </ul>
38  {% endif %}{% endif %}
39  {% endblock %}
40  <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %}
41  <div>
42  {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %}
43  {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %}

这些是我的 models.pyadmin.py

的相关部分
class UserContent(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User, related_name='%(class)s_creator')
    updated_by = models.ForeignKey(User, related_name='%(class)s_updater')

    class Meta:
        abstract = True


class Linetrans(UserContent):
    line = models.ForeignKey(Line)
    translation = models.ForeignKey(Translation)
    text = models.CharField(max_length=400)

    #def __str__(self):
    #    return self.text

    class Meta:
        ordering = ['line']

admin.site.register(Linetrans)

其他型号class非常相似,不会return出错。当 Linetrans 作为内联添加到另一个管理员 class.

时也会发生错误

编辑/更新:我注释掉了模型中的所有其他 str() 方法,果然错误似乎消失了。现在正在尝试查明问题所在。

原来是相关模型中出现了意想不到的空CharField。留下这个答案,因为它可能对其他人有帮助。

通过系统地注释掉模型的 __str__() 方法来解决问题,直到找到有问题的模型。从那里开始识别违规记录。

我遇到了类似的问题。问题是一行的主键为空(我不知道这是怎么发生的)。由于级联问题,我无法删除该行。所以我不得不将 str mmethod 更改为这样的东西。

def __str__(self):
    if self.customerName==None:
        return "ERROR-CUSTOMER NAME IS NULL"
    return self.customerName
def __str__(self):
        return str(self.topic)

使用 str 使其键入字符串。 那就不是非字符串类型了

您还可以从 django shell python manage.py shell 中删除模型中导致此问题的实例。当你处理一个像我这样有很多相关模型的模型时,这会很有帮助。

Typically this problem is caused by altering model fields and migrating, such that the instances are incompatible with each other and related fields

查看您在

中提到的 class
        models.ForeignKey 

问题出在

        __str__() 

这些 classes 之一的方法。 然后,添加

                             or ''

在 return 语句中 class 像这样。

        def __str__(self):
            return self.title or ''

在我的例子中,我有一个不同的模型被另一个模型调用,该模型具有来自 VSCode 的默认代码段:

def __str__(self):
    return

这是导致错误的原因,即使它显示在日志中的另一个地方也是如此。

如果您尝试使用 __str__() 到 return ForeignKeyOneToOneField 的值,这将 return 错误

示例:

def __str__():
    return self.user  # where user is a key to other model class

应该是:

def __str__():
    return self.user.__str__() 
    # Or basically any other way that would explicitly unbox the value inside the related model class.

在我的例子中,我遇到了同样的问题,其起源是:对于 __str__ 函数中使用的字段,数据库中保存了空值。

所以我可以通过以下方式解决问题:

update table
set field_for_STR_use = 'any value'
where field_for_STR_use is null or field_for_STR_use = ''

之后,我只刷新了视图,问题就消失了。

对于这个错误你可以使用两种解决方案

第一个解决方案: 你可以在代码下面注释掉

 def __str__(self):
    return self.id

 #def __str__(self):
 #  return self.id

第二个解决方案:你可以return对象中的字符串

 def __str__(self):
    return str(self.id)

有一个返回非字符串字段的外部引用。我把它改成了字符串字段或者你可以改成str(foreign-key-return-element) name = models.CharField(max_length=200, unique=True) # 文章名称 parent = models.ForeignKey('self',on_delete=models.DO_NOTHING,related_name='category_parent_item', default=None, null=True) # 存储子项 created_at = models.DateTimeField(auto_now=True) # 创建日期 updated_at = models.DateTimeField(auto_now=True) # 更新日期 用户 = models.ForeignKey(get_user_model(),

on_delete=models.DO_NOTHING,related_name='category_update_user',default=None,null=True) #更新文章的用户

def __str__(self):
    return self.name ----------> this was an integer field initially in foreign reference

这对我有用:

    def __str__(self):
    return f"{self.category}"

只需使用“f”字符串