如何在Django admin中的字段中添加填充?

时间:2019-05-17 10:41:19

标签: python django django-admin padding

我正在使用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} padding来设置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。

1 个答案:

答案 0 :(得分:1)

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)
                                 )
相关问题