“gettext()”与“gettext_lazy()”相比在姜戈中

发布于 2024-10-02 05:02:50 字数 410 浏览 4 评论 0原文

我有一个关于使用 ugettext 和 gettext_lazy() 进行翻译的问题。 我了解到,在模型中我应该使用 gettext_lazy() ,而在视图中应该使用 ugettext 。 但是还有其他地方我也应该使用 gettext_lazy() 吗?表单定义又如何呢? 它们之间有性能差异吗?

编辑: 还有一件事。有时,使用 gettext_noop() 代替 gettext_lazy()。正如文档所述, gettext_noop() 字符串仅标记为翻译,并在向用户显示它们之前在最近可能的时刻进行翻译,但我在这里有点困惑,这不是类似于 <代码>gettext_lazy() 做什么?我仍然很难决定应该在我的模型和表单中使用哪一个。

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

Edit:
And one more thing. Sometimes, instead of gettext_lazy(), gettext_noop() is used. As documentation says, gettext_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 gettext_lazy() do? It's still hard for me to decide, which should I use in my models and forms.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

妞丶爷亲个 2024-10-09 05:02:50

gettext()gettext_lazy()

在表单或模型等定义中,您应该使用 gettext_lazy 因为此定义的代码仅执行一次(主要是在 django 的启动上); gettext_lazy 以惰性方式翻译字符串,这意味着,例如。每次你访问模型上的属性名称时,字符串都会被重新翻译 - 这完全是有道理的,因为自从 django 启动以来你可能会用不同的语言查看这个模型!

在视图和类似的函数调用中,您可以毫无问题地使用 gettext ,因为每次调用视图时 gettext 都会重新执行,因此您始终会获得适合请求的正确翻译!

关于 gettext_noop()

正如 Bryce 在他的回答中指出的那样,此函数将字符串标记为可提取用于翻译,但返回未翻译的字符串。这对于在两个地方使用字符串非常有用 - 翻译的和未翻译的。请参见以下示例:

import logging
from django.http import HttpResponse
from django.utils.translation import gettext as _, gettext_noop as _noop

def view(request):
    msg = _noop("An error has occurred")
    logging.error(msg)
    return HttpResponse(_(msg))

gettext() vs. gettext_lazy()

In definitions like forms or models you should use gettext_lazy because the code of this definitions is only executed once (mostly on django's startup); gettext_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 gettext without problems, because everytime the view is called gettext will be newly executed, so you will always get the right translation fitting the request!

Regarding gettext_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 gettext as _, gettext_noop as _noop

def view(request):
    msg = _noop("An error has occurred")
    logging.error(msg)
    return HttpResponse(_(msg))
你げ笑在眉眼 2024-10-09 05:02:50

_noop 的一个绝佳用途是当您想要为开发人员记录一条英文消息,但将翻译后的字符串呈现给查看者时。一个例子是 http://blog.bessas.me/posts/在 django 中使用 gettext/

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/

不忘初心 2024-10-09 05:02:50

惰性版本返回代理对象而不是字符串,在某些情况下它不会按预期工作。例如:

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

会失败,因为最后一行会尝试将 lst 对象序列化为 JSON,并且它会具有代理对象,而不是“client”的字符串。代理对象不可序列化为 json。

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.

久而酒知 2024-10-09 05:02:50

gettext() 可以在函数内部工作但在函数之外不起作用。

gettext_lazy() 可以在内部工作外部函数。

*您最好根据 翻译

;

下面是 gettext() 可以工作的地方:

# "my_app1/views.py"

from django.http import HttpResponse
from django.utils.translation import gettext as _

def hello(request):
    HttpResponse(_("Hello")) # Here

下面是 gettext_lazy() 可以工作的地方:

# "core/settings.py"

from django.utils.translation import gettext_lazy as _

LANGUAGES = (
    ('en', _('English')),
    ('fr', _('French'))
)
# "my_app1/views.py"

from django.http import HttpResponse
from django.utils.translation import gettext_lazy as _

def hello(request): # Here
    HttpResponse(_("Hello"))
# "my_app1/urls.py"

from django.urls import path
from . import views
from django.utils.translation import gettext_lazy as _

app_name = "my_app1"

urlpatterns = [
    path(_('hello'), views.hello, name="hello"),
]        # Here
# "my_app1/models.py"

from django.db import models
from django.utils.translation import gettext_lazy as _

class Person(models.Model):                             # Here
    name = models.CharField(max_length=20, verbose_name=_("name"))

    class Meta:
        verbose_name = _('person') # Here
        verbose_name_plural = _('persons') # Here
# "my_app1/admin.py"

from django.contrib import admin
from django import forms
from .models import Person
from django.utils.translation import gettext_lazy as _

admin.site.site_title = _('My site title') # Here
admin.site.site_header = _('My site header') # Here
admin.site.index_title = _('My index title') # Here

class PersonForm(forms.ModelForm): # Here
    name = forms.CharField(label=_('name')) 

    class Meta:
        model = Person
        fields = "__all__"

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):    
    form = PersonForm
# "my_app1/apps.py"

from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _

class App1Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'my_app1'
    verbose_name = _('my app1') # Here

gettext() can work inside functions but doesn't work outside functions.

gettext_lazy() can work inside and outside functions.

*You better use gettext_lazy() outside functions according to the examples of Translation.

<gettext()>

This below is where gettext() can work:

# "my_app1/views.py"

from django.http import HttpResponse
from django.utils.translation import gettext as _

def hello(request):
    HttpResponse(_("Hello")) # Here

<gettext_lazy()>

This below is where gettext_lazy() can work:

# "core/settings.py"

from django.utils.translation import gettext_lazy as _

LANGUAGES = (
    ('en', _('English')),
    ('fr', _('French'))
)
# "my_app1/views.py"

from django.http import HttpResponse
from django.utils.translation import gettext_lazy as _

def hello(request): # Here
    HttpResponse(_("Hello"))
# "my_app1/urls.py"

from django.urls import path
from . import views
from django.utils.translation import gettext_lazy as _

app_name = "my_app1"

urlpatterns = [
    path(_('hello'), views.hello, name="hello"),
]        # Here
# "my_app1/models.py"

from django.db import models
from django.utils.translation import gettext_lazy as _

class Person(models.Model):                             # Here
    name = models.CharField(max_length=20, verbose_name=_("name"))

    class Meta:
        verbose_name = _('person') # Here
        verbose_name_plural = _('persons') # Here
# "my_app1/admin.py"

from django.contrib import admin
from django import forms
from .models import Person
from django.utils.translation import gettext_lazy as _

admin.site.site_title = _('My site title') # Here
admin.site.site_header = _('My site header') # Here
admin.site.index_title = _('My index title') # Here

class PersonForm(forms.ModelForm): # Here
    name = forms.CharField(label=_('name')) 

    class Meta:
        model = Person
        fields = "__all__"

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):    
    form = PersonForm
# "my_app1/apps.py"

from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _

class App1Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'my_app1'
    verbose_name = _('my app1') # Here
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文