lazy and why to use them in django?

This is a very basic question. I tried to google to find answers that I could understand in simple language. but that did not help. I came across the below snippet of code in Django's UserCreationForm and only then I know something ugettext_lazy _ exists. I have no idea, if it is a django specific module/function , what's its purpose and why it should be used.

There is this article in SO, which discuss more on this. but I want to grasp the fundamentals first. Please enlighten me!

from django.utils.translation import ugettext, ugettext_lazy as _

///// what is the _ means here and why is it used

class UserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """

    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("The two password fields didn't match."),
    }

ugettext is a unicode version of a translatable string.

ugettext_lazy is a "lazy" version of that. Lazy strings are a Django-ism; they are string-like objects that don't actually turn until the real string until the last possible minute. Often, you can't know how to translate a string until late in the process. I don't know what language a browser uses until I can look at their request, so I want the translation string to be "lazy" and not evaluate until it absolutely needs to be rendered in the template, for instance.

For your purpose, it means these will appear as strings--but it also means that they might be overridden by translations. So, for example, you could change the duplicate-username message to _("Sorry, but a user with that name exists. Please try again"). For English-speaking browsers, they'd see your new message. If this string has a translation already registered, though, you'd be breaking it--now the lookup for the Spanish-language version would fail, since it wouldn't find a matching string to yours for Spanish.

For 95% of sites, this doesn't matter, since you won't offer a translated version of your site. If it does, you should read https://docs.djangoproject.com/en/dev/topics/i18n/.

链接地址: http://www.djcxy.com/p/78258.html

上一篇: RenderAction的差异

下一篇: 懒惰,为什么要在Django中使用它们?