我们有一个支持多种语言的 Django 站点。正在尝试添加对多语言的 opensearch 插件支持。
OpenSearch.org 规范使用IETF 语言标签(xx-YY 格式)。默认 Django 设置使用完全匹配。
目前状态下,本站仅支持 xx 形式返回 E404。例子:
http://website.domain/en/...
根据用户配置,浏览器插入语言参数为 xx 或 xx-YY。它需要对双方都有效
- 如果
xx-YY
不可用,网站应提供xx
(母国语言)结果。 - 如果
xx
不可用,网站应提供en
(英文)结果。
支持的 URL 示例:
http://website.domain/fr-YY/...
fall-back to: http://website.domain/fr/...
http://website.domain/xx/...
fall-back to: http://website.domain/en/...
来自 Mozilla 网站的示例 URL:https: //support.mozilla.org/en-US/questions/949545
如何让 Django 支持 IETF 语言标签(xx-YY 格式)?我什至正在寻找在不修改 django 上游代码的情况下实现这一点的提示。
更新:
好吧,官方文档清楚地表明它应该回退(例如:en-us to en),但我的案例引发了 404 错误。
来源:https ://django.readthedocs.io/en/1.5.x/topics/i18n/translation.html
如果基础语言可用但指定的子语言不可用,则 Django 使用基础语言。例如,如果用户指定 de-at(奥地利德语)但 Django 只有 de 可用,则 Django 使用 de。
...
LANGUAGES = ( ('de', _('German')), ('en', _('English')), )
此示例将可用于自动选择的语言限制为德语和英语(以及任何子语言,如 de-ch 或 en-us)。
以下是相关的代码部分:
settings.py
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en'
LANGUAGES = (
( 'ar', "Arabic" ),
( 'en', "English" ),
( 'fr', "French" ),
( 'id', "Indonesian" ),
( 'ja', "Japanese"),
( 'ku', "Kurdish" ),
#( 'ur', "Urdu" ),
( 'ms', "Malay" ),
( 'ml', "Malayalam" ),
#( 'tr', "Turkish" ),
( 'es', "Spanish" ),
( 'pt', "Portuguese"),
#( 'sv', "swedish" )
)
# These are languages not supported by Django core. We have to provide
# their info here so we can use them in our templates. This is mainly
# used in `wui.templatetags.languages`.
EXTRA_LANGUAGES = {
'ku': {
'code': 'ku',
'name': 'Kurdish',
'bidi': True,
'name_local': 'Kurdish'
},
'ms': {
'code': 'ms',
'name': 'Malay',
'bidi': False,
'name_local': 'Malay'
},
}
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns( '',
url( r'^jos2', 'wui.views.jos2' ),
url(r'^r', 'wui.views.one_aya_page'),
url(r'^$', 'wui.views.results'),
# url( r'^admin/', include( admin.site.urls ) ),
)
# These URLs accept the language prefix.
urlpatterns += i18n_patterns('',
url(r'^$', 'wui.views.results'),
url(r'^(?P<unit>\w{3,15})/', 'wui.views.results'),
)
# 404 not found handler
handler404 = 'wui.views.custom_404'