8

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

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

它使我可以获取诸如等之类的网址/en/about-us//pl/about-us/我的默认语言是pl

LANGUAGE_CODE = 'pl'

我想要像 /about-us/ 这样的网址,供客户以波兰语查看我的网站。有没有办法从默认 lang_code 的 url 隐藏 lang_code 前缀?

4

5 回答 5

6

Django>=1.10可以本机处理这个问题。函数中有一个新prefix_default_language参数i18n_patterns

设置prefix_default_language为从默认语言 ( )False中删除前缀。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')),
)

will的回复example.com/contact-us/是英语和example.com/cs/contact-us/捷克语。

于 2017-05-11T09:36:35.303 回答
5

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

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

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

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

于 2013-07-07T22:23:29.907 回答
2

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

  • 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

于 2013-02-13T21:10:31.723 回答
1

您可能想检查yawd-translations正是这样做的。如果您不关心额外的功能(从 db 管理语言),您可以查看urls.translation_patterns方法并middleware.TranslationMiddleware了解它是如何完成的。

于 2013-04-02T13:54:47.400 回答
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

读取request的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',
)
于 2012-10-02T19:24:14.387 回答