1

I'm a django developer, we have been working on 1.3. Now wanted to give a try to latest version i.e. 1.8.1. Since there are many changes from 1.3 to 1.8.1. Wanted to know is there any kind of PhoneField in Django which should store multiple phone numbers in one field. I was thinking of using JSON field for that purpose like

  • Should support multiple numbers
  • Should support "-" in the number
  • Should support country codes like +XX
  • Should support regx validation for phone number.

With JSON field I might be able to achieve that easily but validation would need separate functions.

contact_info = json.JSONField("ContactInfo", default=contact_default)

I found this but don't think much differ from Textfield.

trex
  • 3,848
  • 4
  • 31
  • 54

2 Answers2

3

If you are using PostgreSQL you can use ArrayField.

contact_info = ArrayField(models.CharField(max_length=15), blank=True)

Official documentation here. ArrayField

moonstruck
  • 2,729
  • 2
  • 26
  • 29
1

You can create a function that validates the numbers before being saved to the JSONField or HStoreField.

Example:

import re

def validate_phone_number(phone_number):
    valid_number_pattern = re.compile(r'^(\d{3})-(\d{3})-(\d{4})$')
    
    is_valid = re.match(valid_number_pattern, phone_number)

    return is_valid

def save_number(request):
    if request.METHOD == 'POST':
        phone_number = request.POST['number']
        is_valid = validate_phone_number(phone_number)
        if not is_valid:
            messages.error(request, 'Error, your phone number is not valid!')
            return redirect('main:add_number')
        else:
            [... Add the number(s) to the model's JSONField here ...]
            messages.success(request, 'Success!')
            return redirect('main:index')

Or, you can use a more complex regex from the selected correct answer here: https://stackoverflow.com/a/3868861/3345051

Community
  • 1
  • 1
Hybrid
  • 6,741
  • 3
  • 25
  • 45