Last Updated: March 04, 2016
·
7.768K
· jimbuho

Multilanguage in Django 1.9

  1. Write messages in all python code with: <br>
    
    from django.utils.translation import ugettext as _
    # Sample:
    location = _('Select Your Country')
    </code>
    </pre>
    <br>
  2. Write messages in all HTML templates with: <br>
    
    {% load i18n %}
    <!-- Sample-->
    {% trans "Select Your City" %}
    </code>
    </pre>
    <br>
  3. In settings.py:


    LANGUAGECODE = 'en' ugettext = lambda s: s LANGUAGES = ( ('es', ugettext('Spanish')), ('en', ugettext('English')), ) LOCALEPATHS = ( os.path.join(BASEDIR, 'locale'), ) MIDDLEWARECLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] </code> </pre>
  4. Add URLs:


    url(r'^i18n/', include('django.conf.urls.i18n')), </code> </pre> <br>
  5. Add functionality to change language:
    <br>


    5.1. URLS: url(r'^set-language/', views.set_language, name='set-language'), </code> </pre>

5.2. VIEWS:


def setlanguage(request): return render(request, 'set-language.html', {'LANGUAGES':settings.LANGUAGES, 'SELECTEDLANG':request.LANGUAGE_CODE}) </code> </pre> 5.3. TEMPLATES: <form action="/i18n/setlang/" method="post"> {% csrftoken %} <input name="next" type="hidden" value="/" /> <select name="language"> {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" {% if lang.0 == SELECTEDLANG %}selected{% endif %}>{% if lang.1 == 'Spanish' %}Español{% else %}{{ lang.1 }}{% endif %}</option> {% endfor %} </select> <input type="submit" value="Go" /> </form> </code> </pre> Create language files django-admin.py makemessages -l es Explore language files changes: django-admin.py makemessages -a Install Rosseta to admin traductions: pip install django-rosetta Add to URLs: url(r'^rosetta/', include('rosetta.urls')), </code> </pre> Add to settings.py apps: 'rosetta', In case to be needed (Rosetta do it) recompile: django-admin.py compilemessages IMPORTANT With Rosseta in English language may happens this error: ValueError, 'plural forms expression could be dangerous' To fix it: A. Remove Rosseta (settings y urls) when all translations are done. B. To add Rosseta again, change language to Spanish in settings (LANGUAGECODE) and with setlanguage view. And then apply step A.