Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use ugettext_lazy?

People also ask

What is Ugettext_lazy?

ugettext_lazy is a "lazy" version of that. Lazy strings are a Django-ism; they are string-like objects that don't actually turn into the real string until the last possible minute. Often, you can't know how to translate a string until late in the process.

What is lazy translation in Django?

You have to use lazy translation in cases where: Translation may not be activated (language not selected) when _("some string") is evaluated. Some strings may be evaluated only at startup (eg. in class attributes such as model and form fields definitions)


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))

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/


The lazy version returns a proxy object instead of a string and in some situation it would not work as expected. For example:

def get(self, request, format=None):
   search_str = request.GET.get('search', '')
   data = self.search(search_str)
   lst = []
   lst.append({'name': ugettext_lazy('Client'), 'result': data})
   return HttpResponse(json.dumps(lst), content_type='application/json')

would fail because very last line would try serialize lst object into JSON and instead of a string for "client" it would have a proxy object. The proxy object is not serializeable into json.