django i18n_patterns隐藏来自url的默认lang_code

时间:2012-07-05 16:07:15

标签: django url internationalization url-routing

我正在使用i18n_patterns将当前lang_code的前缀添加到我的网址。

urlpatterns += i18n_patterns('',
    url(r'^', include('blaszczakphoto2.gallery.urls')),
)

它允许我获取/en/about-us//pl/about-us/等网址。 我的默认语言为pl

LANGUAGE_CODE = 'pl'

我希望url喜欢/ about-us /用于在波兰语中查看我的网站的客户。有没有办法从url隐藏lang_code前缀以获取默认的lang_code?

4 个答案:

答案 0 :(得分:6)

这是一个非常简单的包:django-solid-i18n-urls

设置完成后,没有语言前缀的网址将始终使用settings.LANGUAGE_CODE中指定的默认语言。重定向不会发生。

如果url具有语言前缀,则将使用该语言。

此处也回答:https://stackoverflow.com/a/16580467/821594

答案 1 :(得分:1)

我遇到了这个问题并以这种方式解决了:

  • 创建了一个替代i18n_patterns,它不以网站主要语言为前缀(在settings.LANGUAGE_CODE中定义)。

  • 创建了一个替代中间件,它只使用URL前缀语言来激活当前语言。

我没有看到使用这种技术的任何副作用。

代码:

# coding: utf-8
"""
Cauê Thenório - cauelt(at)gmail.com

This snippet makes Django do not create URL languages prefix (i.e. /en/)
for the default language (settings.LANGUAGE_CODE).

It also provides a middleware that activates the language based only on the URL.
This middleware ignores user session data, cookie and 'Accept-Language' HTTP header.

Your urls will be like:

In your default language (english in example):

    /contact
    /news
    /articles

In another languages (portuguese in example):

    /pt/contato
    /pt/noticias
    /pt/artigos

To use it, use the 'simple_i18n_patterns' instead the 'i18n_patterns'
in your urls.py:

    from this_sinppet import simple_i18n_patterns as i18n_patterns

And use the 'SimpleLocaleMiddleware' instead the Django's 'LocaleMiddleware'
in your settings.py:

    MIDDLEWARE_CLASSES = (
    ...
        'this_snippet.SimpleLocaleMiddleware'
    ...
    )

Works on Django >=1.4
"""

import re

from django.conf import settings
from django.conf.urls import patterns
from django.core.urlresolvers import LocaleRegexURLResolver
from django.middleware.locale import LocaleMiddleware
from django.utils.translation import get_language, get_language_from_path
from django.utils import translation


class SimpleLocaleMiddleware(LocaleMiddleware):

    def process_request(self, request):

        if self.is_language_prefix_patterns_used():
            lang_code = (get_language_from_path(request.path_info) or
                         settings.LANGUAGE_CODE)

            translation.activate(lang_code)
            request.LANGUAGE_CODE = translation.get_language()


class NoPrefixLocaleRegexURLResolver(LocaleRegexURLResolver):

    @property
    def regex(self):
        language_code = get_language()

        if language_code not in self._regex_dict:
            regex_compiled = (re.compile('', re.UNICODE)
                              if language_code == settings.LANGUAGE_CODE
                              else re.compile('^%s/' % language_code, re.UNICODE))

            self._regex_dict[language_code] = regex_compiled
        return self._regex_dict[language_code]


def simple_i18n_patterns(prefix, *args):
    """
    Adds the language code prefix to every URL pattern within this
    function, when the language not is the main language.
    This may only be used in the root URLconf, not in an included URLconf.

    """
    pattern_list = patterns(prefix, *args)
    if not settings.USE_I18N:
        return pattern_list
    return [NoPrefixLocaleRegexURLResolver(pattern_list)]

上面的代码可用于: https://gist.github.com/cauethenorio/4948177

答案 2 :(得分:1)

您可能需要检查yawd-translations哪个确实如此。如果您不关心额外的功能(从db管理语言),您可以查看urls.translation_patterns方法和middleware.TranslationMiddleware以了解如何完成。

答案 3 :(得分:0)

这是我的解决方案:

创建django中间件:django_app / lib / middleware / locale.py

from django.utils import translation

    class SwitchLanguageMiddleware(object):

        def process_request(self, request):
            lang = request.GET.get('lang', '')

            if lang:
                translation.activate(lang)
                request.LANGUAGE_CODE = translation.get_language()

        def process_response(self, request, response):
            request.session['django_language'] = translation.get_language()
            if 'Content-Language' not in response:
                response['Content-Language'] = translation.get_language()
            translation.deactivate()

            return response

它读取了请求的get参数,如果它有lang属性,则切换语言。例如:/ about-us /?lang = pl

将此中间件包含到settings.py:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.common.CommonMiddleware',

    'django_app.libs.middleware.locale.SwitchLanguageMiddleware',
)