---
tags: Python, Django
---
django 多國語言
====
### django版本: 2.1
參考網址
https://automationpanda.com/2018/04/21/django-admin-translations/
修改 "settings.py"
```python
LANGUAGE_CODE = 'en-us' # or other appropriate code
USE_I18N = True
USE_L10N = True
LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]
MIDDLEWARE = [
# ...
'django.middleware.locale.LocaleMiddleware',
# ...
]
```
修改urls.py
```python
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.urls import path
urlpatterns = i18n_patterns(
# ...
path('admin/', admin.site.urls),
# ...
# If no prefix is given, use the default language
prefix_default_language=False
)
```
兩個指令建立語言檔
```python
#Generate message files for a desired language
django-admin makemessages -l zh_Hans
#After adding translations to the .po files, compile the messages
django-admin compilemessages
```
## 建立語言切換按鈕
在專案中任何位置放入 templatetags/i18n_switcher.py
內容如下
```python
from django import template
from django.template.defaultfilters import stringfilter
from django.conf import settings
register = template.Library()
def switch_lang_code(path, language):
# Get the supported language codes
lang_codes = [c for (c, name) in settings.LANGUAGES]
# Validate the inputs
if path == '':
raise Exception('URL path for language switch is empty')
elif path[0] != '/':
raise Exception('URL path for language switch does not start with "/"')
elif language not in lang_codes:
raise Exception('%s is not a supported language code' % language)
# Split the parts of the path
parts = path.split('/')
# Add or substitute the new language prefix
if parts[1] in lang_codes:
parts[1] = language
else:
parts[0] = "/" + language
# Return the full new path
return '/'.join(parts)
@register.filter
@stringfilter
def switch_i18n_prefix(path, language):
"""takes in a string path"""
return switch_lang_code(path, language)
@register.filter
def switch_i18n(request, language):
"""takes in a request object and gets the path from it"""
return switch_lang_code(request.get_full_path(), language)
```
自定義 admin頁
```python
{% extends "admin/base_site.html" %}
{% load static %}
{% load i18n %}
<!-- custom filter module -->
{% load i18n_switcher %}
{% block extrahead %}
<link rel="shortcut icon" href="{% static 'images/favicon.ico' %}" />
{% endblock %}
{% block userlinks %}
<li name="" id="" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">語言
<span class="caret"></span>
<ul class="dropdown-menu">
<li><a href="{{ request|switch_i18n:'en' }}">
<span style="font-size:1em;">🇺🇸 English</span>
</a>
</li>
<li><a href="{{ request|switch_i18n:'zh-hant' }}">
<span style="font-size:1em;">🇹🇼 繁體中文</span>
</a>
</li>
</ul>
</a>
</li>
{% endblock %}
```
### 如何整合 vuejs的 i18n ?
https://djaodjin.com/blog/integrating-django-i18-with-jinja2-and-vuejs.blog