Difference Between gettext and gettext_lazy functions in Django

Learn the Difference Between gettext and gettext_lazy functions in Django

Picture of Nsikak Imoh, author of Macsika Blog
Abstract background with the text Difference Between gettext and gettext_lazy functions in Django
Abstract background with the text Difference Between gettext and gettext_lazy functions in Django

This post is part of the tutorial series titled Learn to Use Django with FastAPI Frameworks

Table of Content

There are several utility functions in the Django translation API to help you translate your application.

They are all available in the django.utils.translation module.

For most cases, you will be using gettext() and gettext_lazy(), which were formerly called ugettext() and ugettext_lazy() but deprecated in Django versions below 2.2.X. The “u” prefix stands for “unicode”.

What is the Difference Between gettext() and gettext_lazy()

Here is the difference between the two Django translation functions:

As the name suggests, the “lazy” version of the function holds a reference to the translation string instead of the actual translated text.

This means that the translation occurs when the value is accessed rather than when they are called.

These details should be taken with utmost importance because in a Django project, there are several cases where the code is only executed once (on Django startup).

This occurrence is commonly seen with definition modules like models, forms, and model forms.

Why you Should use gettext_lazy() in Models and Forms instead of gettext()

Here's what would happen if you use gettext() (instead of gettext_lazy()) in a model definition (let's say on field labels):

  1. Django starts up, the default language is English
  2. Django picks the English version of the field labels
  3. The user changes the website language to Spanish
  4. The labels are still displayed in English (because the field definition is called only once; and by the time it was called, the language was other).

To avoid this behavior, you have to properly use the utility functions.

When to use gettext() and gettext_lazy() Functions for Translation

  • gettext_lazy(): should be used in fields, verbose_name, help_text, methods short_description of models.py, labels, help_text, empty_label of forms.py, verbose_name of apps.py.
  • gettext(): should be used in views.py and other modules similar to view functions that are executed during the request process.

Wrap Off

There you have it! I hope you found this post useful somehow.

If you have any questions or need clarification, feel free to reach out to me.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Get the Complete Code of Django and FastAPI Combo Tutorials on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?