2

I'm making a Django form to update users membership to a website. I want to be able to store phone numbers. I found django-phonenumber-field which is great. The only problem is that the form I created for the user to enter their phone number is too specific. If the user doesn't enter their number as "+99999999" then they get an input error. I would like for the user to be able to enter their number a variety of ways: 999-999-9999, 9-999-9999, (999)999-9999, etc. What's the best way to accomplish this?

My code:

models.py

from django.db import models
from phonenumber_field.modelfields import PhoneNumberField


class Member(models.Model):
    """defines a member for annual registration"""
    name = models.CharField(max_length=255)
    mailing_address = models.CharField(max_length=255)
    home_phone = PhoneNumberField()
    other_phone = PhoneNumberField(blank=True)
    email = models.EmailField()

forms.py

from django import forms

from .models import Member


class MembershipForm(forms.ModelForm):
    """form for renewing membership"""

    class Meta:
        model = Member
        fields = ('name',
                  'mailing_address',
                  'home_phone',
                  'other_phone',
                  'email',
                 )

Thank you for any help!

  • You can all characters that aren't numbers from the string and add a `+` to the front using simple string manipulation functions. – Jonesinator Sep 30 '17 at 20:58
  • https://pypi.python.org/pypi/django-phonenumber-field/1.1.0 https://stackoverflow.com/questions/19130942/whats-the-best-way-to-store-phone-number-in-django-models – Harry Sep 30 '17 at 21:05
  • 1
    I'd suggest a regular expression that finds all numbers (or takes out everything that is not a number) in your input string, then giving that to django. There are tons of phone number regex for all around the world. It is _always_ good practice to have some sort of server-side user-input verification, even if it is kind of tedious. – Godron629 Sep 30 '17 at 21:21

1 Answers1

1

That field definition is a custom field in Django. You can create your own custom fields. I would recommend getting the code for the PhoneNumberField, which is open source, and subclassing it to you own field MyPhoneNumberField. Override the validation logic to be as you wish. See the details of how these things work at https://docs.djangoproject.com/en/1.11/ref/forms/validation/

Samantha Atkins
  • 658
  • 4
  • 12