我有一个Django网站,我正试图国际化。到现在为止看起来像这样:
主页:
www.myhomepage.com
另一页:
www.myhomepage.com/content/cities
现在我想尝试这样做:
主页:
www.myhomepage.com/en
www.myhomepage.com/de
另一页:
www.myhomepage.com/en/content/cities
www.myhomepage.com/de/content/cities
关注this和this,我设法让主页工作,因此www.myhomepage.com/en
我看到主页用英文和www.myhomepage.com/de
我用德语看到了。
当我想要转到任何其他页面时,问题就出现了,例如www.myhomepage.com/en/content/cities
。然后,呈现的页面仍然是主页。在更改任何设置以进行国际化之前,www.myhomepage.com/content/cities
正确显示。
我的猜测是问题在于视图渲染或网址,但我无法让它工作。
请注意,www.myhomepage.com
的视图属于一个应用,content/cities
的视图属于其他应用。
这是我的代码:
settings.py
MIDDLEWARE_CLASSES = [
...
'django.middleware.locale.LocaleMiddleware',
...
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
'django.template.context_processors.i18n',
],
},
},
]
from django.utils.translation import ugettext_lazy as _
LANGUAGES = (
('en', _('English')),
('de', _('German')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGE_CODE = 'en-us'
USE_I18N = True
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
urlpatterns += i18n_patterns('',
url(r'^content/', include('content.urls', namespace='content')),
)
views.py
from django.shortcuts import render
def home_view(request):
...
context = {
...
}
#print('request home', request)
return render(request, 'home_template.html', context)
通过激活print语句并加载www.myhomepage.com/en/content/cities
,控制台中会打印以下内容:request home: <WSGIRequest: GET '/en/content/cities/'>
,即使此视图属于home_page。
urls.py
from .views import countries_and_cities
urlpatterns = [
...
url(r'^cities/$', countries_and_cities),
...
]
views.py
from django.shortcuts import render
def countries_and_cities(request):
...
context = {
...
}
return render(request, 'cities_template.html', context)
我也尝试了docs中建议的内容,但没有成功。
来自主应用程序的 urls.py
:
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
from content import views as content_views
content_patterns = ([
url(r'^cities/$', content_views.countries_and_cities, name='cities'),
], 'content')
urlpatterns += i18n_patterns('',
url(r'^content/', include(content_patterns, namespace='content')),
)
我做错了什么?
答案 0 :(得分:1)
我终于找到了问题。
还有另一个网址定义为:
urlpatterns += i18n_patterns(
...
url(r'', include('main.urls')),
...
)
这导致了这个问题,即使在进行国际化之前它也能正常运作。
我刚刚将其更改为:
urlpatterns += i18n_patterns(
...
url(r'^$', include('main.urls')),
...
)
它运作正常。