Projet

Général

Profil

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

Paul Marillonnet, 21 septembre 2022 09:34

Télécharger (2,2 ko)

Voir les différences:

Subject: [PATCH 3/5] widgets: add a PhoneWidget (#69221)

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

  
31 31
import django
32
import phonenumbers
32 33
from django import forms
34
from django.conf import settings
33 35
from django.contrib.auth import get_user_model
34 36
from django.forms.widgets import ClearableFileInput, DateInput, DateTimeInput
35 37
from django.forms.widgets import EmailInput as BaseEmailInput
38
from django.forms.widgets import MultiWidget
36 39
from django.forms.widgets import PasswordInput as BasePasswordInput
37 40
from django.forms.widgets import TextInput, TimeInput
38 41
from django.utils.encoding import force_text
......
395 398
            choices[attribute.name] = '%s (%s)' % (attribute.label, attribute.name)
396 399
        choices['ou__slug'] = _('Organizational unit slug (ou__slug)')
397 400
        return choices
401

  
402

  
403
class PhoneWidget(MultiWidget):
404
    def __init__(self, attrs=None):
405
        prefixes = ((code, f'+{code}') for code in settings.PHONE_COUNTRY_CODES.keys())
406
        widgets = [
407
            forms.Select(attrs=attrs, choices=prefixes),
408
            forms.TextInput(attrs=attrs),
409
        ]
410
        super().__init__(widgets, attrs)
411

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