django 中namespace的问题

在早期的django版本中

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

而我现在使用的是django2.2.3这样写就会出现错误

'Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.'
另外我使用的是path()函数而不是url()函数,再经查看include()函数源代码如下

def include(arg, namespace=None):
    app_name = None
    if isinstance(arg, tuple):
        # Callable returning a namespace hint.
        try:
            urlconf_module, app_name = arg
        except ValueError:
            if namespace:
                raise ImproperlyConfigured(
                    'Cannot override the namespace for a dynamic module that '
                    'provides a namespace.'
                )
            raise ImproperlyConfigured(
                'Passing a %d-tuple to include() is not supported. Pass a '
                '2-tuple containing the list of patterns and app_name, and '
                'provide the namespace argument to include() instead.' % len(arg)
            )
    else:
        # No namespace hint - use manually provided namespace.
        urlconf_module = arg
 
    if isinstance(urlconf_module, str):
        urlconf_module = import_module(urlconf_module)
    patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
    app_name = getattr(urlconf_module, 'app_name', app_name)
    if namespace and not app_name:
        raise ImproperlyConfigured(
            'Specifying a namespace in include() without providing an app_name '
            'is not supported. Set the app_name attribute in the included '
            'module, or pass a 2-tuple containing the list of patterns and '
            'app_name instead.',
        )
    namespace = namespace or app_name
    # Make sure the patterns can be iterated through (without this, some
    # testcases will break).
    if isinstance(patterns, (list, tuple)):
        for url_pattern in patterns:
            pattern = getattr(url_pattern, 'pattern', None)
            if isinstance(pattern, LocalePrefixPattern):
                raise ImproperlyConfigured(
                    'Using i18n_patterns in an included URLconf is not allowed.'
                )
    return (urlconf_module, app_name, namespace)

由urlconf_module, app_name = arg这句可知arg参数是一个二元元组,第一个元素是app的url文件的位置,第二个是app的名字,所以现在的path写为如下所示

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include(('mysite1.urls','mysite1'),namespace='learning_logs')),
    path('users/',include(('users.urls','users'),namespace='users')),
]

有上面的代码为例来看,include()函数中的第一个为urls的文件所在地址,即我有一个app名字叫做users,其中有一个urls的文件,那么第二个参数就是‘users’即urls文件所在的目录名字

posted on 2019-07-19 17:12  之懿  阅读(2254)  评论(0编辑  收藏  举报

导航