Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何向Django admin中的字段添加填充?_Python_Django_Django Admin_Padding - Fatal编程技术网

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

Python 如何向Django admin中的字段添加填充?,python,django,django-admin,padding,Python,Django,Django Admin,Padding,我使用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 = m

我使用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)
我在其中添加了
\uuuu str\uuuu
方法,该方法具有特定格式,其中包含将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                          .

我使用的是Python 3.6.8和Django 2.1.5。

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

def\uuuu str\uuuuuu(自):
非特征空间=u'\xa0'
用户名=self.user.username如果self.user为else“”
返回“{}-{}-{}”.format(str(self.user).ljust(25,非中断空间),
self.view.ljust(30,非中断空间),
str(self.date).ljust(32,非中断空间)
)

我检查了呈现文本的HTML代码,其中没有多个空格,因此它一定是在两者之间的某个地方丢失了。无论如何,谢谢你的把戏,这是一个很好的把戏!!