[PYTHON] Internationalization with django

If you implement a service that is used in many countries or regions with Django, you will want a system that automatically translates by specifying the language of that region. django has a useful translation function, so I'll try using that function.

environment

Clone Django environment

Prepared here Use Minimum configuration website environment with django.

https://github.com/yu-sa/my_site I'll clone Django from.

# git clone https://github.com/yu-sa/my_site.git
# cd my_site

Operating environment construction

# pip install virtualenvwrapper
# mkvirtualenv --python=/path/to/python/2.7.11/bin/python i18n
# pip install django==1.9
# pip install mysql-python
# mysql -u root
> CREATE DATABASE my_site;
> exit
#  python manage.py migrate

Run ranserver

# python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
April 08, 2016 - 17:46:13
Django version 1.9, using settings 'my_site.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

http://127.0.0.1:8000/views/ When you access, a page like the one below will be displayed.

スクリーンショット 2016-04-08 14.50.54.png

At this point, both the page title and the page body are in Japanese. Let's fix this so that it will be automatically converted to English.

Install django-admin-tooles

Use django-admin-tooles to create a translation list, so install

pip install django-admin-tools

Translation support

Create locale folder in the specified hierarchy

my_site
└─my_site
 └─locale

Set the path of the local folder in settings Added "django.middleware.locale.LocaleMiddleware" to MIDDLEWARE_CLASSES. Please note that you can only go to the position to add as follows.

settings.py


# locale
LOCALE_PATHS = (
    os.path.join(FILE_DIR, 'locale'),
)

…………

MIDDLEWARE_CLASSES = [
    ………,
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    ………,
]


Create a message file (django.po) needed for translation Creates a translated message file for the language specified in the -l option. en is English. For Japanese ja.

# django-admin.py makemessages -l en
processing locale en

In django.po, you'll find the words "TOP Page" and "Hello World" currently displayed on the page. I will put the translated characters of these two strings.

django.po


#: my_site/views/index.py:13
msgid "TOP page"
msgstr "Top Page"

#: my_site/views/index.py:14
msgid "Hello World"
msgstr "Hello world"

Then compile this message file to create django.mo.

# django-admin.py compilemessages

You can choose what language you want the body in html to display Set up the form.

index.html


………
<span>
  <form action="{% url 'set_language' %}" method="post">
	{% csrf_token %}
	<input name="next" type="hidden" value="{{ redirect_to }}" />
	<select name="language">
	{% get_available_languages as LANGUAGES %}
	{% get_language_info_list for LANGUAGES as languages %}
	{% for language in languages %}
	<option value="{{ language.code }}" {% if request.LANGUAGE_CODE == language.code %}selected{% endif%}>{{ language.name_local }} ({{ language.code }})</option>
	{% endfor %}
	</select>
	<input type="submit" value="Go" />
  </form>
</span>
………

Register the url set on the form side

my_site/views/urls.py


from django.conf.urls import url, include
from .index import IndexView
 
 
urlpatterns = [
    url(r'^$', IndexView.as_view(), name='api-index'),
    url(r'^i18n/', include('django.conf.urls.i18n')),
]
スクリーンショット 2016-04-11 10.40.19.png

Explanation of translation function

First, the translation flow is as follows

Create a message file for the language you want to translate
↓
Enter the translation content in the message in the message file
↓
Compile message file
↓
Translate the wording into the language you set by setting the translation template tag

GitHub https://github.com/yu-sa/my_site/tree/i18n

I have uploaded the source code implemented this time to branch i18 of the my_site repository. If you are interested, please try cloning.

Recommended Posts

Internationalization with django
Django 1.9 for internationalization
CRUD with Django
Authenticate Google with Django
Django 1.11 started with Python3.6
Upload files with Django
Output PDF with Django
Markdown output with Django
Use Gentelella with django
Twitter OAuth with Django
Getting Started with Django 1
Send email with Django
File upload with django
Use LESS with Django
Pooling mechanize with Django
Use MySQL with Django
Start today with Django
Getting Started with Django 2
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Get started with Django! ~ Tutorial ⑤ ~
Minimal website environment with django
Do Django with CodeStar (Python3.8, Django2.1.15)
Deploy Django serverless with Lambda
Getting Started with Python Django (1)
Create a homepage with django
Get started with Django! ~ Tutorial ④ ~
Django
Getting Started with Python Django (4)
Web application creation with Django
Getting Started with Python Django (3)
Combine FastAPI with Django ORM
Get started with Django! ~ Tutorial ⑥ ~
Save tweet data with Django
Do AES encryption with DJango
Getting Started with Python Django (6)
Combine two images with Django
Getting Started with Django with PyCharm
Real-time web with Django Channels
Double submit suppression with Django
Django REST framework with Vue.js
Use prefetch_related conveniently with Django
Getting Started with Python Django (5)
Login with django rest framework
Qiita API Oauth with Django
Test Driven Development with Django Part 3
reload in django shell with ipython
Steps to develop Django with VSCode
Load Django modules with an interpreter
Test Driven Development with Django Part 6
Measure Django application coverage with Coverage.py
Handle csv files with Django (django-import-export)
HTTPS with Django and Let's Encrypt
Manage Django config files with Python-decouple
Deploy a Django application with Docker
Common html to rent with Django
Django Model with left outer join
Test Driven Development with Django Part 2
Django Tips-Create a ranking site with Django-
Twitter posting application made with Django
Automatically generate model relationships with Django
How to get started with Django