Skip to main content
 首页 » 编程设计

python之Django 如何在 i18n_patterns 中设置默认语言

2025年02月15日27haluo1

settings.py

from django.utils.translation import ugettext_lazy as _ 
LANGUAGE_CODE = 'hi' 
# list of activated languages 
LANGUAGES = ( 
    ('hi', _('Hindi')), 
    ('en', _('English')), 
) 

urls.py

urlpatterns += i18n_patterns( 
    url(r'^', include('howdy.urls')), 
    url(r'^', include('accounts.urls')), 
    url(r'^admin/', admin.site.urls), 
    url(r'^i18n/', include('django.conf.urls.i18n')), 
    url(r'^accounts/', include('allauth.urls')) 
) 

中间件

MIDDLEWARE = [ 
    'django.middleware.security.SecurityMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.common.CommonMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'django.middleware.clickjacking.XFrameOptionsMiddleware', 
    'debug_toolbar.middleware.DebugToolbarMiddleware', 
    'django.middleware.locale.LocaleMiddleware', 
] 

所以我在这里设置的默认值是 "hi" ,但是每当我在没有附加任何语言的情况下点击 URL[private mode] 时,它会在 url 中使用“en”重定向,而不是“嗨”。我在这里缺少什么让它默认指向“hi”语言?

请您参考如下方法:

你在使用 LocaleMiddleware 吗?请参阅:How Django discovers language preference :

LocaleMiddleware tries to determine the user’s language preference by following this algorithm:

  • First, it looks for the language prefix in the requested URL. This is only performed when you are using the i18n_patterns function in your root URLconf. See Internationalization: in URL patterns for more information about the language prefix and how to internationalize URL patterns.

  • Failing that, it looks for the LANGUAGE_SESSION_KEY key in the current user’s session.

  • Failing that, it looks for a cookie. The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.)

  • Failing that, it looks at the Accept-Language HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations.

  • Failing that, it uses the global LANGUAGE_CODE setting.