Domanda

I am trying to make a website available in different languages. I am following some tutorial I found on GitHub (https://github.com/mjp/django-multi-language).

views.py

#! -*- coding: utf-8 -*-
from django.shortcuts import render
from django.utils.translation import ugettext as _


# ──────────────────────────────────────────────────────────────────────────────
def index(request):

    # Rendering the page
    context = { 'foobar':_('Hello !') }
    response = render(request, 'home/index.html', context)
    request.session['django_language'] = 'fr'
    return response

index.html

{% load i18n %}
<p>{{ foobar }}</p>

settings.py

# Project path for further access
PROJECT_PATH = path.realpath(path.dirname(__file__))

# Locale paths
LOCALE_PATHS = (              # Next to the settings.py
    PROJECT_PATH+'/locale/',  # the time I find a better way to
)                             # avoid hard coded absolute path

Localization is quite straightforward, but my page keeps saying Hello ! instead of Bonjour !.


Edit

- documentation/
- locale/          <-- I want it here
- sources/
  - application1/
  - application2/
  - projectname/
    - settings.py
    - ...
    - locale/      <-- Currently here
- toolbox/
È stato utile?

Soluzione

Setting request.session['django_langauge'] is not helpfull in this case. The LocaleMiddleware which I assume you have installed will parse that before the request gets to the view function. You should directly use the translation functions to change language for this.

from django.utils.translation import activate

def index(request):
    activate('fr')
    ....
    return response
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top