1

I want user to input their phone numbers with 10 digits, how to set integer field "phone_no" in order to achieve it ?

I have set it to default but I want to check number input :

models.py

class Documents(models.Model):
    docs_name = models.CharField(max_length=200,verbose_name="Names in Documents")
    item_type = models.CharField(default="", max_length=100,
                             help_text='*Enter the item name you found e.g. Marksheet,key,wallet',verbose_name="Item type" )
    police_station = models.CharField(max_length=255, help_text='*Enter the police station you sending the docs', verbose_name="Police station")
    phone_no = models.IntegerField(default=0, verbose_name="Phone number")
    date = models.DateTimeField(default=timezone.now,verbose_name="Date")
    Description = models.TextField(blank=True, null=True, help_text='*Enter full description about item',verbose_name="Description")
    pay_no = models.IntegerField(default=0,verbose_name="payment number")
    publish = models.BooleanField(default=False)

    image = models.ImageField(default="add Item image",
                          upload_to="DocsImage",blank=False, verbose_name="Images")


"""docstring for Documents"""
def __str__(self):
    return self.docs_name
2
  • are you sure to use an IntegerField for the phone number ? what if it begins with 0 ? Commented Jul 21, 2019 at 7:17
  • any way to achieve it, and of course it starts with zero. Please help!! Commented Jul 21, 2019 at 7:19

1 Answer 1

4

You can use validators to achieve this. They are functions (or any callable) that you can plug in the Field declaration to check some conditions.

Firstly, in this case, you should use a models.CharField(verbose_name="Phone number"...) to store the phone number, in case they begin by 0.

Next we have to perform tests to check if the value contains only digits, and only 10.

Option 1: Custom validator

The first way is to create the validator yourself in order to run the tests you want exactly:

  • Create the function that will raise an error if the tests fail :

    def validate_digit_length(phone):
        if not (phone.isdigit() and len(phone) == 10):    
            raise ValidationError('%(phone)s must be 10 digits', params={'phone': phone},)
    

    You can store this function next to the model, or in a separate file and import it.

  • Then plug this function in the field declaration, on the parameter validators (type list) :

    phone_no = models.CharField(verbose_name="Phone number", max_length=10,  
        validators=[validate_digit_length], default='1234567890')
    

Option 2: Use Built-in validators

You can also find built-in validators in django, for all the generic cases.

With this Charfield phone_no, the max_length parameter will check the max size, so we need to check the minimum size (10) and if characters are digits. We can achieve this with MinLengthValidator and int_list_validator :

from django.core.validators import MinLengthValidator, int_list_validator

phone_no = models.CharField(verbose_name="Phone number", max_length=10,
    validators=[int_list_validator(sep=''),MinLengthValidator(10),], 
    default='1234567890')

Another link to explore :
What's the best way to store Phone number in Django models

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.