Skip to content

Instantly share code, notes, and snippets.

@umutcoskun
Created January 12, 2017 11:26
Show Gist options
  • Save umutcoskun/2bc10b16f74a55b950532e2782c53633 to your computer and use it in GitHub Desktop.
Save umutcoskun/2bc10b16f74a55b950532e2782c53633 to your computer and use it in GitHub Desktop.
Django custom filter that formats phone numbers using 'phonenumbers' module.
@register.filter(name='format_phonenumber')
def format_phonenumber(phone, country='TR'):
"""
Usage:
{{ user.phone|format_phonenumber }}
{{ user.phone|format_phonenumber: 'TR' }}
"""
import phonenumbers
return phonenumbers.format_number(
phonenumbers.parse(phone, country),
phonenumbers.PhoneNumberFormat.NATIONAL,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment