Model a 6-digit numeric postal code in django

Question:

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.

Asked By: user3848207

||

Answers:

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'))],
    )
Answered By: Willem Van Onsem