我正在使用 Django Admin 访问某些项目的数据。为了能够有一个正确的看法,我有一些课程:
class Whatever(models.Model):
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)
date = models.DateTimeField(blank=False, null=False, default=datetime.utcnow)
view = models.CharField(max_length=256, blank=False, null=False)
我添加了__str__
具有特定格式的方法,其中包含将 X 字符设置为字段的{:X}
填充:
def __str__(self):
username = self.user.username if self.user else ""
return "{:25} - {:30} - {:32}".format(self.user., self.view, self.date)
然而,在 Django 管理员中,所有的填充都被忽略了,所以我得到的只是一组关于格式的行:
bla - my_view - 2019-05-14 17:18:57.792216+00:00
another_user - another_view - 2019-05-14 16:05:27.644441+00:00
没有任何填充,而我想要的是:
bla - my_view - 2019-05-14 17:18:57.792216+00:00
another_user - another_view - 2019-05-14 16:05:27.644441+00:00
在普通 Python 中,如果我这样做:
class M(object):
def __init__(self):
self.a = "hola"
self.b = "adeu"
def __str__(self):
return "{:25} - {:30}.".format(self.a, self.b)
它运作良好:
>>> print(m)
hola - adeu .
我在 Python 3.6.8 和 Django 2.1.5 中。
Django 管理员不会修改您的模型字符串表示。当您的浏览器呈现文本时会发生空格截断。所以为了强制不可破坏的空间,你可以这样做:
def __str__(self):
nonBreakSpace = u'\xa0'
username = self.user.username if self.user else ""
return "{} - {} - {}".format(str(self.user).ljust(25, nonBreakSpace),
self.view.ljust(30, nonBreakSpace),
str(self.date).ljust(32, nonBreakSpace)
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句