When should I use ugettext_lazy?


Question

I have a question about using ugettext and ugettext_lazy for translations. I learned that in models I should use ugettext_lazy, while in views ugettext. But are there any other places, where I should use ugettext_lazy too? What about form definitions? Are there any performance diffrences between them?

Edit: And one more thing. Sometimes, instead of ugettext_lazy, ugettext_noop is used. As documentation says, ugettext_noop strings are only marked for translation and translated at the latest possible momment before displaying them to the user, but I'm little confused here, isn't that similar to what ugettext_lazy do? It's still hard for me to decide, which should I use in my models and forms.

1
125
6/5/2018 12:38:47 PM

Accepted Answer

ugettext() vs. ugettext_lazy()

In definitions like forms or models you should use ugettext_lazy because the code of this definitions is only executed once (mostly on django's startup); ugettext_lazy translates the strings in a lazy fashion, which means, eg. every time you access the name of an attribute on a model the string will be newly translated-which totally makes sense because you might be looking at this model in different languages since django was started!

In views and similar function calls you can use ugettext without problems, because everytime the view is called ugettext will be newly executed, so you will always get the right translation fitting the request!

Regarding ugettext_noop()

As Bryce pointed out in his answer, this function marks a string as extractable for translation but does return the untranslated string. This is useful for using the string in two places – translated and untranslated. See the following example:

import logging
from django.http import HttpResponse
from django.utils.translation import ugettext as _, ugettext_noop as _noop

def view(request):
    msg = _noop("An error has occurred")
    logging.error(msg)
    return HttpResponse(_(msg))
176
8/5/2019 10:24:18 AM

An excellent use of _noop, is when you want to log a message in English for the developers, but present the translated string to a viewer. An example of this is at http://blog.bessas.me/posts/using-gettext-in-django/


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon