从网址Django的i18n_patterns隐藏默认LANG_CODE(django i18n_p

2019-06-26 01:43发布

我使用的是i18n_patterns当前LANG_CODE的前缀添加到我的网址。

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

这allowes我得到像URL /en/about-us//pl/about-us/等我的默认语言为pl

LANGUAGE_CODE = 'pl'

我想URL喜欢/美国/客户端浏览我的网站在波兰语lenguage。 有没有办法从网址为默认LANG_CODE隐藏LANG_CODE前缀?

Answer 1:

这里是一个非常简单的包: Django的固国际化的URL

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

如果网址将有语言的前缀,那么这种语言将被使用。

还回答了在这里: https://stackoverflow.com/a/16580467/821594 。



Answer 2:

的Django >=1.10可以本地处理这个问题。 有一个新的prefix_default_language在参数i18n_patterns功能。

设置prefix_default_languageFalse将删除默认语言(前缀LANGUAGE_CODE )。 添加翻译到现有的站点时,使当前的URL不会改变这可能是有用的。

来源: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#language-prefix-in-url-patterns

例:

# Main urls.py:
urlpatterns = i18n_patterns(
    url(r'^', include('my_app.urls', namespace='my_app')), 
    prefix_default_language=False
)

# my_app.urls.py:
url(r'^contact-us/$', ...),

# settings:
LANGUAGE_CODE = 'en' # Default language without prefix

LANGUAGES = (
    ('en', _('English')),
    ('cs', _('Czech')),
)

的响应example.com/contact-us/将以英语和example.com/cs/contact-us/捷克。



Answer 3:

我面对这个问题,解决了这个办法:

  • 创建一个替代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



Answer 4:

你可能想看看姚色,翻译这正是这么做的。 如果你不关心额外的功能(管理从DB语言),你可以看看urls.translation_patterns方法和middleware.TranslationMiddleware ,看看它是如何做。



Answer 5:

这是我的解决方案:

创建Django的中间件:django_app / lib目录/中间件/ 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属性,然后切换语言。 例:/约-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',
)


文章来源: django i18n_patterns hide default lang_code from url