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

2024-04-16 07:16:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Django管理访问一些项目的数据。为了能有一个正确的观点,我有一些课程:

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__方法,该方法具有特定的格式,其中包含^{} 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 admin中,所有的填充都被忽略,所以我得到的只是一组关于格式的行:

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                          .

我使用的是python3.6.8和Django 2.1.5。你知道吗


Tags: django方法selfviewfalsetruedatemodels
1条回答
网友
1楼 · 发布于 2024-04-16 07:16:46

Django admin不会修改您的模型字符串表示形式。当浏览器呈现文本时,会发生空格截断。因此,为了强制不可破坏的空间,可以执行以下操作:

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)
                                 )

相关问题 更多 >