名称 'urlpatterns' 在进行翻译时未定义 (+= i18n_patterns)

name 'urlpatterns' is not defined when doing translation (+= i18n_patterns)

我想在 URL 模式中添加语言前缀,就像 django 文档主页一样。按照这个 example 我的 urls.py 看起来像这样:

from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin

from myapp import views
from myapp.views import MyFirstView, MySecondView

myapp_patterns = [
    url(r'^$', views.CategoryView, name='index'),
    url(r'^(?P<name>[a-zA-Z0-9_]+)/$', MyFirstView.as_view(), name='detail'),
    url(r'^(?P<name>[a-zA-Z0-9_]+)/mysecond_view/$', MySecondView, name='mysecond_view')
]

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^categories/', include(myapp_patterns)),
    url(r'^', views.LandingView),
]

这有效,但现在当我添加 += i18n_patterns

urlpatterns += i18n_patterns [
    url(r'^admin/', admin.site.urls),
    url(r'^categories/', include(myapp_patterns)),
    url(r'^', views.LandingView),
]

我得到错误:NameError: name 'urlpatterns' is not defined

我确实添加了 LocalMiddleware

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

还有这个:

LANGUAGE_CODE = 'en-us'

USE_I18N = True

USE_L10N = True

LOCALE_PATHS = (
        os.path.join(BASE_DIR, 'locale'),
)

我不明白 urlpatterns 怎么突然没有定义了。 我在这里做错了什么?

主要是因为+=urlpatterns.

之前没有定义

您应该从赋值 = 开始定义它。