Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 426831
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T19:31:07+00:00 2026-05-12T19:31:07+00:00

I am trying to do a PhoneField that convert the value as a standardized

  • 0

I am trying to do a PhoneField that convert the value as a standardized value.

In this case, I want to use this clean method.

def clean(self):
    phone = self.cleaned_data.get('phone')

    # Is it already standardized ?
    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

    # If not, it must be a french number.
    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

If I use it in a form, it works well.
But I would like to use it as a form field.

I tried to do like that :

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 = None

        return super(PhoneInput, self).render(name, value, attrs)

class PhoneField(models.CharField):
    widget = PhoneInput

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 16
        super(PhoneField, self).__init__(*args, **kwargs)

    def get_internal_type(self):
        return "CharField"

    def clean(self, value):
        phone = super(PhoneField, self).clean(value)

        # 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

But the clean method is never called. Can you help me ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T19:31:07+00:00Added an answer on May 12, 2026 at 7:31 pm

    You are mixing up the model fields and form fields.

    Form Fields need to be first defined and then corresponding model Fields need to be asked to use those form fields for a model form.

    See specifying-the-form-field-for-a-model-field documentation

    Basically you need to define a method called formfield on the model field

    def formfield(self, **kwargs):
        # This is a fairly standard way to set up some defaults
        # while letting the caller override them.
        defaults = {'form_class': MyFormField}
        defaults.update(kwargs)
        return super(HandField, self).formfield(**defaults)
    

    The Field that you have created above, has a clean method, that is a requirement for a form field, not a model field

    So, now you should define a form field (the one you have defined, except extend it from forms.CharField, not models.CharField) and then define a model field, as per model field creation definitions, and include the method like above.

    Alternatively and simplistically, you could just choose to define a form field, and in the model form, override the default form field of this particular modelfield. (Altho’ in this case validation doesnt take place unless data is entered from that modelform)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Trying to make this jQuery filter that uses .find case-insensitive. For example, when the
I am getting following error when I am trying to use Convert.FromBase64String The input
I am trying to use this jQuery plugin http://bassistance.de/jquery-plugins/jquery-plugin-validation so I can validate a
Trying to write a procedure that given a value and a list, it deletes
I am trying to get this code to make a square that will follow
I'm trying to create a validation that enforce the :phone field to be 9
Trying to figure out how I can do this properly. The print_r looks like
Trying to implement LoaderManager + CursorLoader. In onFinish method adapter should swap its cursor
trying to figure out why this is happening - I have an input text
trying to use the beforeSave hook with some server side validation and throwing a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.