Why do you need "import gettext_lazy as _" in this Django code?

I want to add a new field to my Django models.py

from django.core.validators import RegexValidator
from django.db import models

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

This code gave me an error NameError: name '_' is not defined.

After some googling, I found a solution but don't understand the solution. To fix this problem, I added the line from django.utils.text import gettext_lazy as _

Now, the code becomes like this;

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'))],
    )

What is the purpose of from django.utils.text import gettext_lazy as _ ? Why does it fix the error?

I am using Django v4

Back to Top