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