0

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:

enter image description here

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?

galfisher
  • 1,122
  • 1
  • 13
  • 24
Andrew
  • 89
  • 2
  • 9
  • Related to https://stackoverflow.com/questions/7354212/format-an-un-decorated-phone-number-in-django? – meshy Apr 11 '18 at 19:15

1 Answers1

0

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.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284