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

  • Home
  • SEARCH
  • 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 get my css / C# functions to look like this: body {
Trying to find some simple SQL Server PIVOT examples. Most of the examples that
Trying to make a make generic select control that I can dynamically add elements
Trying to keep all the presentation stuff in the xhtml on this project and
Trying to do this sort of thing... WHERE username LIKE '%$str%' ...but using bound
Trying to perform a single boolean NOT operation, it appears that under MS SQL
Trying to honor a feature request from our customers, I'd like that my application,
I have a table that I added a column called phone - the table
Trying to find the attribute value from a url hash. // URL http://url.com/index.html#link //
Trying to setup an SSH server on Windows Server 2003. What are some good

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.