我有類似的問題,所以我發送我的決議,以節省您的時間。
主(urls.py)
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
]
urlpatterns += i18n_patterns(
url(r'^', include('index.urls', namespace='index')),
)
(index.urls.py)
from django.conf.urls import url
from django.views.generic import TemplateView
from django.utils.translation import ugettext_lazy as _
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='index/index.html'), name='index'),
url(_(r'^python-programming/$'), TemplateView.as_view(template_name='index/new_page.html'),
name='new_page'),
]
創建模板標籤中,我們支持所有語言返回當前位置的URL(index.templatetags .helper_tags.py)
from django.template import Library
from django.core.urlresolvers import resolve, reverse
from django.utils.translation import activate, get_language
register = Library()
@register.simple_tag(takes_context=True)
def change_lang(context, lang=None, *args, **kwargs):
"""
Get active page's url by a specified language
Usage: {% change_lang 'en' %}
"""
path = context['request'].path
url_parts = resolve(path)
url = path
cur_language = get_language()
try:
activate(lang)
url = reverse(url_parts.view_name, kwargs=url_parts.kwargs)
finally:
activate(cur_language)
return "%s" % url
創建中間件來更改站點語言,當用戶點擊alt ernative連結此子網站,但在不同的語言 (middleware.py)
from django.utils import translation
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class LangBasedOnUrlMiddleware(MiddlewareMixin):
@staticmethod
def process_request(request):
if hasattr(request, 'session'):
active_session_lang = request.session.get(translation.LANGUAGE_SESSION_KEY)
if active_session_lang == request.LANGUAGE_CODE:
return
if any(request.LANGUAGE_CODE in language for language in settings.LANGUAGES):
translation.activate(request.LANGUAGE_CODE)
request.session[translation.LANGUAGE_SESSION_KEY] = request.LANGUAGE_CODE
它添加到(設置。PY)剛過模板LocaleMiddleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'our_app.middleware.LangBasedOnUrlMiddleware',
]
使用範例:
{% load i18n %}
{% load helper_tags %}
{% get_available_languages as languages %}
{% for lang_code, lang_name in languages %}
<a href="{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% change_lang lang_code %}">
{% endfor %}