Django unable to translate language - django

I want to translate my website to CH, but no response after I followed the online instruction. Did I miss something?
I have changed the language code in settings.py.
settings.py:
import os
import django_heroku
from django.utils.translation import gettext_lazy as _
LANGUAGES = (
('en', ('English')),
('zh-Hant', _('Traditional Chinese')),
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
...
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMP_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.i18n',
'django.template.context_processors.debug',
....]}
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-Hant'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale')
]
Added the tag for translation in html
base.html:
{% load i18n %}
<!DOCTYPE html>
<html>
....
home.html:
{% extends "base.html" %}
{% load i18n %}
{% block content %}
{% trans "Let's translate this" %}
....
Updated msgstr in ....\locale\zh-Hant\LC_MESSAGESdjango.po:
msgid "Let's translate this"
msgstr "來翻譯這個"

Updated msgstr in ....\locale\zh-Hant\LC_MESSAGESdjango.po:
For traditional Chinese:
zh-hant in your config, and your directory should be named zh_Hant.
See the locale directory: https://github.com/django/django/tree/master/django/contrib/auth/locale
locale name
A locale name, either a language specification of the form ll or a combined language and country specification of the form ll_CC. Examples: it, de_AT, es, pt_BR, sr_Latn. The language part is always in lowercase. The country part is in titlecase if it has more than 2 characters, otherwise it’s in uppercase. The separator is an underscore.
and languages keys with lowercase:
LANGUAGES = (
('en', _('English')),
('zh-hant', _('Traditional Chinese')),
)

Change your language code so that you have LANGUAGES like this;
LANGUAGES = (
('en', gettext('English')),
('ja', gettext('Japanese')),
('it', gettext('Italian')),
('zh-hant', gettext('Chinese')),
)
I've tested this on a multi-lingual site that I have.
python manage.py makemessages -l zh-hant
python manage.py compilemessages
Django admin then looks like this by default;

Related

variable inside blocktranslate not translated when makemessages

I make a simple template like this
<button class="btn">{% blocktranslate %}{{ greeting }} Quy!{% endblocktranslate %}</button>
with greeting equals hello.
I have added the following MIDDLEWARE, and LANGUAGE_CODE = 'vi'. Everything else is left as default.
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
and
LANGUAGE_CODE = "vi"
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LANGUAGES = [
('vi', _('Vietnamese')),
('en', _('English')),
]
After running django-admin makemessages -l vi, the .po file is created
msgid "%(greeting)s Quy!"
msgstr ""
I added
# vi/LC_MESSAGES/django.po
msgid "hello"
msgstr "chào"
or
# en/LC_MESSAGES/django.po
msgid "hello"
msgstr "hi"
and then run django-admin compilemessages but "hello" shown up instead of "chào" or "hi". Why I cannot translate the variable
I tries it with tag translate, and it works if I send variable greeting as "hello", whereas for blocktranslate I need _("hello")

Django command makemessages does not generate string marked for translations for files in templates directory

I have project in Django==2.2.12
and this is part of my settings:
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, "templates")],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"django.template.context_processors.static",
],
},
},
]
LANGUAGE_CODE = "pl"
TIME_ZONE = "Europe/Warsaw"
USE_I18N = True
USE_L10N = True
USE_TZ = False
LANGUAGES = (
('pl', gettext('Polish')),
('en', gettext('English')),
)
When I execute:
django-admin makemessages --locale=en
It generates .po files with string to translate in locale directory from .py files but it completly skips .txt files that are located in my templates directory. For example it does not generate string for translation for my text.txt file with following content:
{% load i18n %}
{% blocktranslate %}
string to translate
{% endblocktranslate %}
Make sure to use {%trans 'your string %}
Use this command to update .po files: python manage.py makemessages -l ar --no-wrap --no-location
Remove #fuzzy if it's above what you want to translate
Run python manage.py compilemessages
I hope this helps!

Django's get_current_language always returns "en"

In my Django 2.0 site, I want to set the lang atribute of the html tag to the current locale's language. In my base.html which other templates extend, I use get_current_language in the following way
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">
...
</html>
The site has translations for multiple languages. If I switch the language in the browser, I see the correct translations, but the lang attribute will always contain en.
In my settings.py I have
USE_I18N = True
LANGUAGE_CODE = 'en-us'
and based on the suggestion of Goran the following middleware order
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
The LANGUAGES setting is unset.
As suggested by Kostadin Slavov I have tried printing the language from the view. It seems that get_current_language calls django.utils.translation.get_language, so I have inserted the following in my view
from django.utils import translation
print(translation.get_language())
It prints the correct value (eg de when accessing the view with a browser set to German).
What else am I missing?
I tried to simulate your environment with these steps:
$ cd ~
$ python3 -m venv ~/venvs/mysite
$ source ~/venvs/mysite/bin/activate
$ pip install django==2.0.8
$ django-admin startproject mysite
Then I updated the generate code as in your example:
mysite/settings.py
...
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
...
mysite/urls.py
from django.contrib import admin
from django.urls import path
from django.views.generic.base import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name='base.html'), name='home'),
path('admin/', admin.site.urls),
]
templates/base.html
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">
<body>
<pre>LANGUAGE_CODE = {{ LANGUAGE_CODE }}</pre>
<body>
</html>
With the Django generated code and my few above updates I can see different language code if I switch the language of my browser visiting http://localhost:8000/ after starting it with:
$ python manage.py runserver
Try my steps on your local environment and check if it works, and then compare your project to the code above.
Update
Try to use diffsettings to see "differences between the current settings file and Django’s default settings".
Had the same problem. In my case, the function was called async and always returned the default language.
SOLUTION: pass language from 'main' context.
Code like in this example:
def get_context_data( self, **kwargs ):
context = super().get_context_data(**kwargs)
lng_code = get_language() # -> 'de'
#sync_to_async
def get_data():
context['data1'] = Model1.objects.filter(language==get_language()) # get_language() -> 'en'
#sync_to_async
def get_data2():
...
#sync_to_async
def get_data3():
...
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
asyncio.gather(
get_data1(),
get_data2(),
get_data3()
))
loop.close()

Django internationalization not working

My django is not executing translations that i define in my *.po files.
I have my setup like this:
MainFolder:
locale
en
LC_MESSAGES
django.po
django.mo
de
LC_MESSAGES
django.po
django.mo
app1
settings.py
app2
....
in my settings.py i have everything enabled i think:
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'en'
LANGUAGES = (
('en', _('English')),
('de', _('German')),
)
TEMPLATE_CONTEXT_PROCESSORS = (
....
'django.core.context_processors.static',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
)
let's say my django.po file contains an example like this:
msgid "Home"
msgstr "Home22222"
and i use this in my template file:
{% trans "Home" %}
The home is not being replace by Home22222
It stays the same, even when i remove the LocaleMiddleware.
i did ran
makemessages --locale=en
and afterwards:
compilemessages
I am using Python 2.7 and django 1.6.4

About django translation template {% trans “something” %} in different systems

I know, I'm asking about something similar, requested a lot of times. But with a different point of view.
I'm working on a little django project. After developed the base functionalities, now I'm fighting with the multilanguage.
I was able to use a simple test template in my windows laptop. But when I copy this project to the test (CentOS) server it doesn't work.
Hereafter what I did.
The base environment (both systems) is virtualenv with python 2.7, django 1.5, mysql-python 1.2.3 and django-localeURL 1.5. gettext v.1.7.
These are the relevant options of settings.py (Note: I use django-localeURL application)
# Django settings for contact_site project.
import os.path
PROJECT_DIR = os.path.dirname(__file__) # this is not Django setting.
# ... skip
LANGUAGE_CODE = 'it'
#...skip
USE_I18N = True
USE_L10N = True
#...skip
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
# LocaleMiddleware after SessionMiddleware: it needs sessions
# commented out LocaleMiddleware to avoid conflict with LocaleURLMiddleware
# 'django.middleware.locale.LocaleMiddleware',
# LocaleURLMiddleware to manage multi language urls
'localeurl.middleware.LocaleURLMiddleware',
# CommonMiddleware after LocaleURLMiddleware or will not work APPEND_SLASH
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
# ... skip
_ = lambda s: s
LANGUAGES = (
('en', _(u'English')),
('it', _(u'Italiano')),
('fr', _(u'Francais')),
)
LOCALE_PATHS = (
# in windows laptop
'C:/...skip.../virtualenvs/djprj/contact_site/locale',
# in centos staging server
# '/var/www/html/virtualenvs/djprj/contact_site/locale',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.i18n',
'django.contrib.auth.context_processors.auth',
)
TEMPLATE_DIRS = (
# ...skip
os.path.join(PROJECT_DIR, "templates"),
)
INSTALLED_APPS = (
# localeurl to manage multi language urls. it must be the 1st one!
'localeurl',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# ... skip
# my application
'contact',
)
# ... skip
my project urls.py (the home only):
# ... skip
urlpatterns += patterns('',
url(r'^$', 'contact_site.views.home', name='home'),
)
my views.py (the home only):
#... skip
def home(request):
return render(request, 'minimalistic.html', {})
and finally my minimalistic template:
{% load debug_tags %}
{% load i18n %}
<!DOCTYPE html>
<html>
<head>
<title>TITLE</title>
</head>
<body>
{# {% set_trace %} #}
<p>{% trans "Hello" %}</p>
<p>{% blocktrans %}Hello guys{% endblocktrans %}</p>
lingua richiesta: {{ request.LANGUAGE_CODE }}
</body>
</html>
Then I produced the dictionaries of messages using
django-admin.py makemessages --all
I edited the dictionaries (using poedit)
and finally, running development server, in windows I saw the coveted result:
peeking from browser http://127.0.0.1:8000/it gave me Salve...
while getting http://127.0.0.1:8000/en gave me Hello ...
Unfortunatly in the stage system I got Hello ... from both URLs.
Just to be safe, in centos I tried even
django-admin.py compilemessages
this operation was ok, but without different results about the minimalistic.html template rendering
And last, yes, I cleared my browser cache between tests.
Any suggestion about what am I missing? How can I debug this strange behaviour?
Well, I'm sorry and a little embarassed.
Today, debugging django/utils/translate/trans_real.py, I have realized the presence of a subtle typo mistake in the staging server settings.py file.
I cannot count how many times yesterday I checked that configuration file, missing the point!
Sorry again