Projet

Général

Profil

0003-widgets-add-a-PhoneWidget-70486.patch

Paul Marillonnet, 19 octobre 2022 17:10

Télécharger (2,31 ko)

Voir les différences:

Subject: [PATCH 3/4] widgets: add a PhoneWidget (#70486)

 src/authentic2/forms/widgets.py | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
src/authentic2/forms/widgets.py
28 28
import re
29 29
import uuid
30 30

  
31
import phonenumbers
31 32
from django import forms
33
from django.conf import settings
32 34
from django.contrib.auth import get_user_model
33 35
from django.forms.widgets import ClearableFileInput, DateInput, DateTimeInput
34 36
from django.forms.widgets import EmailInput as BaseEmailInput
37
from django.forms.widgets import MultiWidget
35 38
from django.forms.widgets import PasswordInput as BasePasswordInput
36 39
from django.forms.widgets import TextInput, TimeInput
37 40
from django.utils.encoding import force_str
......
387 390
            choices[attribute.name] = '%s (%s)' % (attribute.label, attribute.name)
388 391
        choices['ou__slug'] = _('Organizational unit slug (ou__slug)')
389 392
        return choices
393

  
394

  
395
class PhoneWidget(MultiWidget):
396
    def __init__(self, attrs=None):
397
        prefixes = (
398
            (code, '{area} (+{code})'.format(area=value['area'], code=code))
399
            for code, value in settings.PHONE_COUNTRY_CODES.items()
400
        )
401
        widgets = [
402
            forms.Select(attrs=attrs, choices=prefixes),
403
            forms.TextInput(attrs=attrs),
404
        ]
405
        super().__init__(widgets, attrs)
406

  
407
    def decompress(self, value):
408
        try:
409
            # phone number stored in E.164 international format, no country specifier needed here
410
            pn = phonenumbers.parse(value)
411
        except phonenumbers.NumberParseException:
412
            pass
413
        else:
414
            if pn:
415
                code = str(pn.country_code)
416
                # retrieve the string representation from pn.national_number integer
417
                raw_number = '0' * (pn.number_of_leading_zeros or 0) + str(pn.national_number)
418
                return [code, raw_number]
419
        return [settings.DEFAULT_COUNTRY_CODE, value]
390
-