i18n 다국어 기능 적용하는 방법
윈도우에서 아래와 같이 에러가 발생한다면, gettext/iconv 프로그램을 설치한다.
CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed.
- https://mlocati.github.io/articles/gettext-iconv-windows.html
settings.py에 아래와 같이 업데이트를 한다
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware', # (중요) 정해진 위치에 삽입해줍니다.
'django.middleware.common.CommonMiddleware',
...
]
LANGUAGE_CODE = 'en-us'
#기본값으로 제공될 언어를 적어줍니다.
LANGUAGES = [ # 사용하고자 하는 언어를 모두 적어줍니다.
('ko', 'Korean'),
('en-us', 'English'),
('es', 'Spanish'),
]
LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]
#번역된 파일이 저장될 경로를 설정해 줍니다.
지원되는 언어 코드 확인
http://www.i18nguy.com/unicode/language-identifiers.html
Using Language Identifiers (RFC 3066)
Using Language Identifiers (RFC 3066) Language identifiers as specified by RFC 3066, can have the form language, language-country, language-country-variant and some other specialized forms. The guidelines for choosing between language and language-country
www.i18nguy.com
! 중요 ) url에 i18n의 경로를 입력해 준다. 이 설정을 해줘야 나중에 template에서 form 등을 이용한 언어 변환을 수행할 수 있다. 기본으로 제공되는 기능을 사용하지 않을 경우, 직접 view를 통해 수정이 가능하다.
템플릿에 적용하자
{% load i18n %} # i18n을 로드해줍니다.
{{_(" ")}}
<h1> {% trans "Hello World" %} </h1>
혹은
<h1> {% translate "Hello World" %} </h1>
<h1> {% trans "Hello World" as boy="BOY", girl="GIRL"%} </h1>
{% blocktrans %}
{% endblocktrans %}
언어별 번역 용지 생성을 하자
# 전체 메시지 파일 만들기
python manage.py makemessage -a
# 개별적 메시지 파일 만들기
python manage.py makemessages -l 언어코드
예) python manage.py makemessages -l ko
python manage.py makemessages -l en
#, fuzzy 표시가 있으면 해당 부분의 주석을 삭제한다.
번역 결과물을 생성하자 django.po -> django.mo
python manage.py compilemessages
사용자에게 번역어 선택지를 제공
만약 직접 view에서 데이터를 확인하고 수정하고자 한다면
translation.get_language() 함수를 view에서 사용하면 된다.
혹은 다음과 같이 사용할 수도 있다.
from django.utils.translation import activate
def test_uses_index_template(self):
activate('en')
response = self.client.get(reverse("home"))
self.assertTemplateUsed(response, "taskbuster/index.html")
혹은 아래와 같이 session을 이용하여 다양하게 이용할 방법을 모색할 수도 있다.
def index(request):
if translation.LANGUAGE_SESSION_KEY in request.session:
del(request.session[translation.LANGUAGE_SESSION_KEY])
translation.activate('en')
request.session[translation.LANGUAGE_SESSION_KEY] = 'en'
msg = _("안녕하세요")
return HttpResponse(msg)
참고 자료 :
[장고] i18n: 다국어 기능 사용법
장고에서 기본적으로 제공하는 다국어 지원 기능인 i18n의 사용법에 대해 알아보겠습니다. 1. 장고 프로젝트 생성 먼저, 장고 프로젝트를 생성합니다. cmd: django-admin startproject 프로젝트명 이해의
query.tistory.com
https://kimdoky.github.io/django/2018/08/30/django-taskbuster-5/
TaskBuster Django Tutorial – Part 5 - Internationalization and Localization. Languages and Time zones
on August 30, 2018 under django 15 minute read 이번 파트에서는 국제화(Internationalization), 현지화(Localization), 표준 시간대(Time Zones)에 대해 다룹니다. 우리 웹 사이트는 두 가지 다른 언어를 정의하고 각 언어
kimdoky.github.io
[웹 프로그래밍 스쿨 16주차] 장고 9주차
장고에서의 번역 기능인 I18N(Internationalization)을 사용해보자. 기본 언어를 변경하는 방법은 settings.py에서 다음과 같이 설정해준다. LANGUAGE_CODE = 'ko-kr' TIME_ZONE = 'Asia/Seoul' TIME_ZONE을 'asia/seoul'로 해줘
inoru.tistory.com
https://velog.io/@jewon119/Django-%EA%B8%B0%EC%B4%88-Django-Translation
1. Django Tutorial(Airbnb) - Django Translation
🌈 Django Translation > ### 🔥 Settings & TransTag > ### 🔥 Translation File > ### 🔥 getcurrentlanguage > ### 🔥 Python code Translation 1. Setting
velog.io
https://phrase.com/blog/posts/methods-difference-django-templates/
The Difference between _() and {% trans %} in Django Templates
How do the _() and {% trans %} approaches in Django templates differ, and why should be one preferable rather than the other? A comparison.
phrase.com
https://runebook.dev/ko/docs/django/topics/i18n/translation?page=7
Django - 메시지 파일 컴파일 메시지 파일을 만들고 변경할 때마다 gettext를 사용하여 보다 효율적
메시지 파일을 만든 후 - 그리고 변경할 때마다 - gettext 에서 사용할 수 있도록 보다 효율적인 형식으로 컴파일해야 합니다 . django-admin compilemessages 유틸리티 를 사용하여 이 작업을 수행합니다.
runebook.dev
'Study > django' 카테고리의 다른 글
django MQ 시리즈 1편 - task queue (1) : Asynchronous Tasks With Django and Celery (1) | 2023.03.04 |
---|---|
django에서 redis 사용하기 1편 (캐시 사용: 데이터 / 세션) (1) | 2023.02.16 |
django admin - raw_id_fields, search_fields problem (0) | 2022.12.19 |
devspoon-portfolio-blog 오픈소스에 admin 기능 구현하기 (0) | 2022.12.11 |
Django ORM Cookbook 학습 정리 (0) | 2022.12.07 |
댓글