Table of Content
- Difference Between gettext() And gettext_lazy() functions in Django
- What is the Difference Between gettext() and gettext_lazy()
- Why you Should use gettext_lazy() in Models and Forms instead of gettext()
- When to use gettext() and gettext_lazy() Functions for Translation
- Wrap Off
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):
- Django starts up, the default language is English
- Django picks the English version of the field labels
- The user changes the website language to Spanish
- 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.