我在models.py文件中定义了一个模型:
class Tutor(models.Model):
FirstName = models.CharField(max_length=50)
LastName = models.CharField(max_length=50)
Email = models.EmailField(max_length=100)
PhoneNumber = models.CharField(max_length=10)
RequestedHours = models.DecimalField(max_digits=3, decimal_places=1)
def __str__(self):
return str(self.FirstName + " " + self.LastName)
我想创建一个页面,在一个易于快速阅读的表格中显示所有这些信息。我大部分时间都设法这么做了,但是我总是发现10位数的电话号码在没有分隔符的情况下更难以阅读。目前,显示输出如下所示:
表格的代码如下:
<div class="table-background">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr class="bg-info">
<th colspan="2">Tutor</th>
</tr>
</thead>
<tbody>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td>{{ tutor.FirstName }}</td>
<td>{{ tutor.LastName }}</td>
</tr>
<tr>
<th>Email</th>
<th> Phone Number</th>
</tr>
<tr>
<td>{{ tutor.Email }}</td>
<td>{{ tutor.PhoneNumber }}</td>
</tr>
<tr>
<th colspan="2">Requested Hours</th>
</tr>
<tr>
<td colspan="2">{{ tutor.RequestedHours }}</td>
</tr>
</tbody>
</table>
我有什么方法可以修改CharField
PhoneNumber
的输出,以便我可以将其显示为000-000-0000?
答案 0 :(得分:0)
您应该在视图中对其进行格式化,但在模板方面:
{% with pn=tutor.PhoneNumber|to_list %}
{{ pn|slice:":3"|join:'' }}-{{ pn|slice:"3:6"|join:'' }}-{{ pn|slice:"6:"|join:''}}
{% endwith %}
您也可以修改您的模型:
class Tutor(models.Model):
FirstName = models.CharField(max_length=50)
LastName = models.CharField(max_length=50)
Email = models.EmailField(max_length=100)
PhoneNumber = models.CharField(max_length=10)
RequestedHours = models.DecimalField(max_digits=3, decimal_places=1)
def __str__(self):
return str(self.FirstName + " " + self.LastName)
def get_formatted_phone(self):
return '{}-{}-{}'.format(self.PhoneNumber[:3],
self.PhoneNumber[3:6],self.PhoneNumber[6:])
然后在你的模板中:
{{ tutor.get_formatted_phone }}
但是这种东西真的属于视图。