Django i18n_patterns没有斜杠

时间:2017-02-21 15:55:00

标签: python django django-i18n

我正试图摆脱网址上的尾随斜杠。目前,网络服务器成功删除了斜杠,APPEND_SLASH = false一切正常但我的本地化主页有问题:

http://example.com/en/ - ok
http://example.com/en - Page not found (404)

Django tried these URL patterns, in this order:

^admin/
^en/

The current URL, en, didn't match any of these.

这是我的urls.py设置:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

urlpatterns += i18n_patterns(
    url(r'^$', views.index, name='index'),
)

可以使这些i18n_patterns无斜线工作吗?

1 个答案:

答案 0 :(得分:0)

我最终创建了一个执行以下操作的中间件:

from django.shortcuts import redirect
from django.utils import translation

def add_i18npatterns_trailing_slash(get_response):
    def middleware(request):
        response = get_response(request)
        if response.status_code == 404:
            language_code = translation.get_language()
            if request.path.endswith(language_code):
                return redirect(f'{request.path}/')
        return response
    return middleware