-1

In the PhoneNumber field for django, how do you allow users to input phone numbers without the leading +1 in the beginning?

This will be a form they fill out.

class Phone(models.Model):
    name = models.CharField(max_length=30)
    phoneNumber = PhoneNumberField()
thatguy
  • 97
  • 9

1 Answers1

0

It looks like your users are using the Django admin.

First, create a form for your model with a custom clean_<fieldname> method that parses the number into E.164 format before storing it.

Something like this should do it (I'm not including the whole class or the imports; this is just a sample clean_ method):

def clean_phoneNumber(self):
    phone_number = self.cleaned_data['phoneNumber']

    # Replace 'US' with whatever type of number it is
    # See https://github.com/daviddrysdale/python-phonenumbers
    parsed_number = phonenumbers.parse(phone_number, 'US')

    return phonenumbers.format_number(
        parsed_number,
        phonenumbers.PhoneNumberFormat.E164,
    )

Then create a model admin class for your model and set its form to the form you just created.

Aside: Consider using phone_number instead of phoneNumber. That's much more idiomatic. See PEP 8.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257