如何修复与“__str__”相关的 Django 管理页面错误
How to fix Django admin page error related to `__str__`
由于数据库 table 中的空字段 (null=True
),管理页面出现 None type
错误。跟随 和 return self.author or '' + self.post_title[:40]
的答案并修复了错误。
现在如何让 post 的作者和标题同时出现在管理页面中。以前的(损坏的)代码:return self.author + ', ' + self.post_title[:40]
,但是一旦我添加 or ''
,+
之后的部分就停止工作了。
如果使用return self.author or '' + self.post_title[:40]
,则解释为
return (self.author) or ('' + self.post_title[:40])
因此 return self.author
,或者如果作者是 None
(或任何其他具有真实性的值 False
),空字符串与 self.post_title[:40]
.
您可以通过以下方式实现此逻辑:
def __str__(self):
return f'<strong>{self.author or ""}</strong>, {self.post_title[:40]}'
由于数据库 table 中的空字段 (null=True
),管理页面出现 None type
错误。跟随 return self.author or '' + self.post_title[:40]
的答案并修复了错误。
现在如何让 post 的作者和标题同时出现在管理页面中。以前的(损坏的)代码:return self.author + ', ' + self.post_title[:40]
,但是一旦我添加 or ''
,+
之后的部分就停止工作了。
如果使用return self.author or '' + self.post_title[:40]
,则解释为
return (self.author) or ('' + self.post_title[:40])
因此 return self.author
,或者如果作者是 None
(或任何其他具有真实性的值 False
),空字符串与 self.post_title[:40]
.
您可以通过以下方式实现此逻辑:
def __str__(self):
return f'<strong>{self.author or ""}</strong>, {self.post_title[:40]}'