简体   繁体   中英

How do I change how a CharField is displayed?

I have a model defined as such in my models.py file:

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)

I want to create a page that displays all of this information in a table that is easy to read quickly. I have managed to do so for the most part, but I have always found 10-digit phone numbers to be more difficult to read without separators. Currently, the display output looks like this:

在此处输入图片说明

And the code for the table looks like this:

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

Is there any way for me to modify the output of the CharField PhoneNumber so that I can get it to display as 000-000-0000?

You should really format it in your view, but on the template side:

{% with pn=tutor.PhoneNumber|to_list %}
 {{ pn|slice:":3"|join:'' }}-{{ pn|slice:"3:6"|join:'' }}-{{ pn|slice:"6:"|join:''}}
{% endwith %}

Your could also modify your model:

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

Then in your template:

{{ tutor.get_formatted_phone }}

But this sort of stuff really belongs in the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM