Skip to content

Instantly share code, notes, and snippets.

@Natim
Created June 28, 2012 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Natim/3010241 to your computer and use it in GitHub Desktop.
Save Natim/3010241 to your computer and use it in GitHub Desktop.
Django French Phone Template Tag
from intranet.widgets import PhoneField
class Restaurant(models.Model):
phone = PhoneField(_(u'Téléphone de réservation'), help_text=_(u"Veuillez entrer votre numéro sous la forme : 03 90 87 65 43 ou +33.390876543"))
@register.filter(name='phone')
def phone(value):
"""
1. Transforme un numéro +33.384289468 en 03.84.28.94.68 pour une meilleure lisibilité.
"""
if value.startswith('+33.'):
# get 9 or 10 digits, or None:
mo = re.search(r'\d{9,10}', value)
# Si le numéro n'est pas standardisé, on ne le modifie pas.
if mo is None: return value
# add a leading 0 if they were just 9
digits = mo.group().zfill(10)
# now put a dot after each 2 digits
return " ".join(re.findall(r'(\d\d)',digits))
else:
return re.sub(r'\+(\d{2,3})\.(\d{9,11})', r"(+\1) \2", value)
################
# Phone Widget
################
EMPTY_VALUES = (None, '')
class PhoneInput (forms.TextInput):
def render(self, name, value, attrs=None):
if value not in EMPTY_VALUES:
value = phone_render(value)
else:
value = phone_render('')
return super(PhoneInput, self).render(name, value, attrs)
class PhoneFormField(forms.CharField):
widget = PhoneInput
def clean(self, value):
phone = super(PhoneFormField, self).clean(value)
#print "PHONE =", phone
# Si le numéro n'est pas vide on traie les infos saisies
if phone != "":
# Le numéro contient-il un indicatif ?
if phone.startswith('+'):
mo = re.search(r'^\+\d{2,3}\.\d{9,11}$', phone)
if not mo:
raise forms.ValidationError(_(u'Vous devez entrer un numéro de téléphone. (+33.389520638 ou 0389520638).'))
else:
return phone
# Pas d'indicatif : on est en France par défaut
phone = re.sub("\D", "", phone) # Suppression des caractères séparateurs
mo = re.search(r'^\d{10}$', phone) # Numéro à 10 chiffres
if not mo:
raise forms.ValidationError(_(u'Vous devez entrer un numéro de téléphone. (+33.389520638 ou 0389520638).'))
else:
phone = mo.group()[-9:]
return u'+33.%s' % phone
# Le numéro est vide, on ne fait rien
else:
#print "PHONE vide"
return phone
class PhoneField(models.CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 16
super(PhoneField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return "CharField"
def formfield(self, form_class=PhoneFormField, **kwargs):
return super(PhoneField, self).formfield(form_class=form_class, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment