Home > Software engineering >  Model a 6-digit numeric postal code in django
Model a 6-digit numeric postal code in django

Time:08-01

I would like to define a 6-digit numeric postal code in Django models.py.

At first, I tried this;

postal_code = models.PositiveIntegerField(blank=False)

However, postal codes can have leading zeros such as 000157. PositiveIntegerField is not suitable for it.

If I use CharField, the field can accept alphabets which are not valid for postal codes.

How do I define a 6-digit numeric postal code in django models.py?

I am using Django v4.

CodePudding user response:

You can use a validator, for example by working with a RegexValidator [Django-doc]:

from django.core.validators import RegexValidator
from django.db import models
from django.utils.text import gettext_lazy as _


class MyModel(models.Model):
    postal_code = models.CharField(
        max_length=6,
        validators=[RegexValidator('^[0-9]{6}$', _('Invalid postal code'))],
    )

CodePudding user response:

You should use validators for it

six_digit_code = models.PositiveIntegerField(validators=[MinValueValidator(100000), MaxValueValidator(999999)])
  • Related