Django

⌘K
  1. Home
  2. Django
  3. Django তে কিভাবে কাজ করতে...
  4. Internationalization and Localization

Internationalization and Localization

I’ll create a comprehensive tutorial on implementing multilanguage support in a Django project. This will serve as documentation for your multilanguage setup.

Here’s a full tutorial on implementing multilanguage support in a Django project:

Django Multilanguage Support Tutorial

1. Install Django and Set Up Your Project

First, ensure you have Django installed. If not, install it using pip:

pip install django

Create a new Django project:

django-admin startproject myproject
cd myproject

2. Install and Configure Gettext

For Windows:

  1. Download gettext utilities from https://mlocati.github.io/articles/gettext-iconv-windows.html
  2. Extract the downloaded zip file to a location (e.g., C:\Program Files\gettext-iconv)
  3. Add the bin directory to your system PATH:
  4. Open System Properties > Advanced > Environment Variables
  5. Edit the Path variable
  6. Add the new path (e.g., C:\Program Files\gettext-iconv\bin)

Verify the installation:

msgfmt --version

For macOS/Linux:

Gettext is usually pre-installed. If not, install it using your package manager.

3. Configure Django Settings

Edit your settings.py file:

from django.utils.translation import gettext_lazy as _
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# ... other settings ...

LANGUAGE_CODE = 'en'

USE_I18N = True
USE_L10N = True

LANGUAGES = (
    ('en', _('English')),
    ('bn', _('Bangla')),
)

LOCALE_PATHS = [
    BASE_DIR / 'locale',
]

MIDDLEWARE = [
    # ... other middleware ...
    'django.middleware.locale.LocaleMiddleware',
    # ... other middleware ...
]

TEMPLATES = [
    {
        # ... other settings ...
        'OPTIONS': {
            'context_processors': [
                # ... other context processors ...
                'django.template.context_processors.i18n',
            ],
        },
    },
]

4. Update URLs Configuration

Edit your urls.py file:

from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('i18n/', include('django.conf.urls.i18n')),
]

urlpatterns += i18n_patterns(
    path('admin/', admin.site.urls),
    # Add your other URL patterns here
    prefix_default_language=False
)

5. Create Locale Directories

Create a locale directory in your project root and all apps root folder:

mkdir locale

6. Prepare Your Python Code for Translation

Use the gettext function (usually aliased as _) to mark strings for translation:

from django.utils.translation import gettext as _

def my_view(request):
    output = _("Welcome to my site.")
    return render(request, 'my_template.html', {'message': output})

7. Prepare Your Templates for Translation

In your HTML templates, use the {% trans %} template tag:

{% load i18n %}

<h1>{% trans "Welcome to my site" %}</h1>

<p>{% trans "This is a translatable string." %}</p>

For block translations:

{% blocktrans %}
    This is a block of text that
    can span multiple lines.
{% endblocktrans %}

8. Create Message Files

Run the following command to create or update the message files:

python manage.py makemessages -l bn

This will create or update the file locale/bn/LC_MESSAGES/django.po.

9. Translate the Strings

Edit the django.po file. For each msgid, provide the corresponding translation in msgstr:

#: path/to/your/file.py:123
msgid "Welcome to my site"
msgstr "আমার সাইটে স্বাগতম"

10. Compile Message Files

After translating, compile the message files:

python manage.py compilemessages

This creates django.mo files, which Django uses for translations.

11. Set Up Language Switching

Create a template snippet for language switching:

{% load i18n %}

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

Include this snippet in your base template.

12. Restart Your Server

After making these changes, restart your Django development server:

python manage.py runserver

13. Testing

  1. Visit your site and ensure the language switcher is visible.
  2. Switch between languages and verify that the content changes accordingly.
  3. Check that all marked strings are being translated.

Troubleshooting

If translations aren’t working:

  1. Ensure USE_I18N = True in settings.py
  2. Verify that LocaleMiddleware is in MIDDLEWARE
  3. Check that .po files are in the correct directory
  4. Make sure you’ve run compilemessages
  5. Restart the Django server after changes
  6. Clear your browser cache
  7. Check your browser’s language settings

Best Practices

  1. Use gettext_lazy for model fields and other places where the string is evaluated at import time.
  2. Keep your translations up to date by regularly running makemessages.
  3. Use context markers in your translations for ambiguous terms.
  4. Consider using django-rosetta for an admin interface for translations.

By following this tutorial, you should have a fully functional multilanguage Django project. Remember to keep your translations updated as you add new content to your site.

How can we help?