27

Could you explain what principal difference between ugettext and ugettext_lazy?

When I'm trying to

return HttpResponse(ugettext_lazy("Hello"))

I see nothing, but

return HttpResponse(ugettext("Hello"))

is working.

Why?

Igor Pochechuev
  • 312
  • 1
  • 3
  • 8

1 Answers1

43

ugettext is used to load a translation of a string right now. ugettext_lazy returns an object that can eventually be turned into a string. You need that if the ugettext_lazy call is evaluated before the proper locale has been set.

ugettext_lazy can be used where you use a Unicode object. Double-check your HTML output, it might look like this:

<django.utils.functional...>

and the browser is ignoring it all as an unrecognized tag.

You don't need a lazy translation in this case, because you are immediately using the string. If you really want to continue with ugettext_lazy for some reason, try this:

return HttpResponse(ugettext_lazy("Hello").encode('utf-8'))

See the docs for more information.

Community
  • 1
  • 1
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 3
    I think `ugettext_lazy` is more useful in `models.py`. – Sergey Orshanskiy Jun 10 '14 at 04:09
  • 2
    So let me see if I understood you. `ugettext` is useful when you are inside a method or function (like a view for example), or in places that are called after the settings & co have been loaded. `ugettext_lazy` is more useful when wanting to translate class properties and such (as @SergeyOrshanskiy suggested when defining a model or a form) which are loaded when the server starts and need lazy loading. Right? – Eduard Luca Sep 17 '14 at 11:51
  • 1
    @EduardLuca asa e :) It's the same principle as using ``reverse_lazy`` instead of ``reverse``. You may use ``reverse_lazy`` on a class based view to define the ``succes_url`` for example, in which case the reverse shall not be evaluated until it is needed – Mihai Zamfir Nov 22 '14 at 14:25