Охватываемые темы: Configuration, Translating strings in Python, Translating in templates, Creating translation files.
Configuration
# settings.py
LANGUAGE_CODE = 'ru'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
('ru', 'Русский'),
('en', 'English'),
]
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware',
]
LOCALE_PATHS = [BASE_DIR / 'locale']
Translating strings in Python
from django.utils.translation import gettext_lazy as _
class Task(models.Model):
class Status(models.TextChoices):
TODO = 'todo', _('К выполнению')
DONE = 'done', _('Выполнено')
title = models.CharField(_('заголовок'), max_length=200)
# In views.py
from django.utils.translation import gettext as _
def my_view(request):
message = _('Задача создана успешно')
return HttpResponse(message)
Translating in templates
{% load i18n %}
<h1>{% trans "Мои задачи" %}</h1>
<p>{% blocktrans with count=task_count %}У вас {{ count }} задач{% endblocktrans %}</p>
Creating translation files
# Collect strings for translation
python manage.py makemessages -l en
# File locale/en/LC_MESSAGES/django.po
# msgid "К выполнению"
# msgstr "To Do"
# Compile
python manage.py compilemessages
Switching languages
# URL for changing the language
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
] + i18n_patterns(
path('tasks/', include('tasks.urls')),
)
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.path }}">
<select name="language">
{% get_available_languages as languages %}
{% for code, name in languages %}
<option value="{{ code }}">{{ name }}</option>
{% endfor %}
</select>
<button type="submit">Switch</button>
</form>
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!