简体   繁体   中英

Django 1.9 - url internationalization

I am trying to setup a project in Django 1.9 and I have trouble to translate the home page.

I would like to redirect my users to /en or /fr when they hit the home page.

So I checked the documentation but it's not quite clear for me.

In my settings.py, I added this (from doc: url internationalization ):

MIDDLEWARE_CLASSES += [
    'django.middleware.locale.LocaleMiddleware',
]

I also have this:

LANGUAGE_CODE = 'en'
DEFAULT_LANGUAGE = 'en'
LANGUAGES = (
    ('en', 'English'),
    ('fr', 'Français'),
)
TIME_ZONE = 'America/Toronto'
USE_I18N = True
USE_L10N = True
USE_TZ = True

In my urls.py, I added:

# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.utils.translation import ugettext_lazy as _
from django.views.generic.base import TemplateView

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name="index.html"), name='home'),
    url(_(r'^privacy-policy/$'), TemplateView.as_view(template_name="privacy-policy.html"), name='privacy-policy'),
]

When I run the server and go to localhost:8000, there is no redirect to /en or /fr

What I am doing wrong ?

I'm not exactly sure about django 1.9, but in 1.8 you need to declare your i18n urlpatterns this way :

# your_project/your_project/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns

urlpatterns += i18n_patterns(
    url(r'^test$', 'your_package.views.test', name='test'),
)

We made an article on my company blog a few month ago if it can help you http://www.metod.io/en/blog/2015/05/05/django-i18n-part-1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM