How is internationalization and localization implemented in Django?
Internationalization and Localization in Django can be achieved through the following steps:
- Set the language and time zone in settings.py.
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
- In template files that require internationalization and localization, use the {% trans %} tag to mark text that needs to be translated.
{% trans "Hello, World!" %}
- Use the functions from the django.utils.translation module to translate text in view functions that require internationalization and localization.
from django.utils.translation import gettext as _
def my_view(request):
output = _("Hello, World!")
return HttpResponse(output)
- To generate the translation file, execute the following command in the project’s root directory:
python manage.py makemessages -l zh_Hans
- Next, edit the generated .po file and fill in the translated text in the msgstr field.
- Finally, execute the following command to compile the translation files:
python manage.py compilemessages
By following the above steps, you can enable internationalization and localization in Django. When users visit the website, Django will automatically display the corresponding translated text based on their language settings.