Django 错误"包含的 URLconf 似乎没有任何模式"



我正在尝试为视图SearchFilterMixin编写一个 mixin,它有一个cookie_path类变量:

class SearchFilterMixin(FilterMixin, SearchMixin):
# Path to send cookies to. Should be set to the path of the model's ListView
# in accordance with our naming convention.
cookie_path = '/'
def get(self, request, *args, **kwargs):
self.query_dict = self.query_dict_from_params_or_cookies(request)
return super().get(request, *args, **kwargs)
def render_to_response(self, context, **response_kwargs):
response = super().render_to_response(context, **response_kwargs)
response.set_cookie('filters', self.request.GET.urlencode(), path=self.cookie_path)
return response
@staticmethod
def query_dict_from_params_or_cookies(request):
"""
If no query parameters are sent with the request, obtain them from a cookie.
"""
return request.GET or QueryDict(request.COOKIES.get('filters'))

在继承视图中,我尝试将cookie_path设置为反向 URL,reverse('dashboard:families')

from dashboard.views.base import (
DashboardAccessMixin, OrderingMixin,
SearchMixin, FilterMixin, HistoryView, SearchFilterMixin
)

class ListBase(DashboardAccessMixin, OrderingMixin, SearchFilterMixin):
cookie_path = reverse('dashboard:families')

但是,当我尝试此操作时,我的开发服务器崩溃并显示以下错误:

django.core.exceptions.Improperly Configuration:包含的URLconf 'lucy.urls'似乎没有任何模式。如果您在文件中看到有效的模式,则问题可能是由循环导入引起的。

以下是完整的回溯:

Performing system checks...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1124100d0>
Traceback (most recent call last):
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/lucy/urls.py", line 25, in <module>
from dashboard.views.utils import reverse_params
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/dashboard/views/__init__.py", line 28, in <module>
from .families import (
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/dashboard/views/families.py", line 38, in <module>
class ListBase(DashboardAccessMixin, OrderingMixin, SearchFilterMixin):
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/dashboard/views/families.py", line 60, in ListBase
cookie_path = reverse('dashboard:families')
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/base.py", line 60, in reverse
app_list = resolver.app_dict[ns]
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 348, in app_dict
self._populate()
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 288, in _populate
for pattern in reversed(self.url_patterns):
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 414, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'lucy.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

事实上,如果我甚至尝试在 Django shell 中反转该 URL,同一行会触发错误:

NoReverseMatch: None 不是已注册的命名空间

这里再次是完整的回溯:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py shell
Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from django.urls import reverse
In [2]: reverse('dashboard:families')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/base.py in reverse(viewname, urlconf, args, kwargs, current_app)
76             try:
---> 77                 extra, resolver = resolver.namespace_dict[ns]
78                 resolved_path.append(ns)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py in namespace_dict(self)
341             self._populate()
--> 342         return self._namespace_dict[language_code]
343 
KeyError: None
During handling of the above exception, another exception occurred:
NoReverseMatch                            Traceback (most recent call last)
<ipython-input-2-565d352d036d> in <module>()
----> 1 reverse('dashboard:families')
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/base.py in reverse(viewname, urlconf, args, kwargs, current_app)
58             # Lookup the name to see if it could be an app identifier.
59             try:
---> 60                 app_list = resolver.app_dict[ns]
61                 # Yes! Path part matches an app in the current Resolver.
62                 if current_ns and current_ns in app_list:
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py in app_dict(self)
346         language_code = get_language()
347         if language_code not in self._app_dict:
--> 348             self._populate()
349         return self._app_dict[language_code]
350 
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py in _populate(self)
286         apps = {}
287         language_code = get_language()
--> 288         for pattern in reversed(self.url_patterns):
289             if isinstance(pattern, RegexURLPattern):
290                 self._callback_strs.add(pattern.lookup_str)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/utils/functional.py in __get__(self, instance, cls)
33         if instance is None:
34             return self
---> 35         res = instance.__dict__[self.name] = self.func(instance)
36         return res
37 
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py in url_patterns(self)
403     def url_patterns(self):
404         # urlconf_module might be a valid set of patterns, so we default to it
--> 405         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
406         try:
407             iter(patterns)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/utils/functional.py in __get__(self, instance, cls)
33         if instance is None:
34             return self
---> 35         res = instance.__dict__[self.name] = self.func(instance)
36         return res
37 
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py in urlconf_module(self)
396     def urlconf_module(self):
397         if isinstance(self.urlconf_name, six.string_types):
--> 398             return import_module(self.urlconf_name)
399         else:
400             return self.urlconf_name
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/importlib/__init__.py in import_module(name, package)
124                 break
125             level += 1
--> 126     return _bootstrap._gcd_import(name[level:], package, level)
127 
128 
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/importlib/_bootstrap.py in _gcd_import(name, package, level)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/importlib/_bootstrap.py in _find_and_load(name, import_)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/importlib/_bootstrap.py in _load_unlocked(spec)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/importlib/_bootstrap_external.py in exec_module(self, module)
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
~/Documents/Dev/lucy/lucy-web/lucy/urls.py in <module>()
23 
24 from lucy_web import views as lucy_web_views
---> 25 from dashboard.views.utils import reverse_params
26 
27 
~/Documents/Dev/lucy/lucy-web/dashboard/views/__init__.py in <module>()
26     ExpertCreate, ExpertUpdate)
27 
---> 28 from .families import (
29     FamilyList, FamilyCSV, FamilyCSVMailing, FamilyHistory,
30     FamilyCreate, FamilyUpdate, FamilyActivate, FamilyCreateEnterpriseSessions)
~/Documents/Dev/lucy/lucy-web/dashboard/views/families.py in <module>()
36 
37 
---> 38 class ListBase(DashboardAccessMixin, OrderingMixin, SearchFilterMixin):
39     queryset = Family.objects.all().prefetch_related(
40         'lucy_guide',
~/Documents/Dev/lucy/lucy-web/dashboard/views/families.py in ListBase()
58         '-package__company__name'
59     ]
---> 60     cookie_path = reverse('dashboard:families')
61 
62     def get_queryset(self):
~/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/base.py in reverse(viewname, urlconf, args, kwargs, current_app)
85                     )
86                 else:
---> 87                     raise NoReverseMatch("%s is not a registered namespace" % key)
88         if ns_pattern:
89             resolver = get_ns_resolver(ns_pattern, resolver)
NoReverseMatch: None is not a registered namespace
In [3]: 

似乎我不能将某个视图的反向 URL 用作该视图的类变量的值,对吗?如果是这样,我该如何解决这个问题?我应该在__init__()方法中定义self.cookie_path吗?

更新

在评论之后,以下是lucy/urls.py的内容:

"""lucy URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import:  from my_app import views
2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
1. Add an import:  from other_app.views import Home
2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views, REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.base import RedirectView
from two_factor.admin import AdminSiteOTPRequired
from markdownx import urls as markdownx
from lucy_web import views as lucy_web_views
from dashboard.views.utils import reverse_params

class LucyAdminSite(AdminSiteOTPRequired):
def login(self, request, extra_context=None):
return_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME))
redirect_url = reverse_params(
'dashboard:mfa-setup', params={REDIRECT_FIELD_NAME: return_to})
return HttpResponseRedirect(redirect_url)

admin.site.__class__ = LucyAdminSite
admin.autodiscover()
urlpatterns = [
url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *nDisallow: /", content_type="text/plain")),
url(r'^admin', RedirectView.as_view(url='/dashboard', permanent=False)),
url(
r'^reset/(?P<uidb64>[0-9A-Za-z_-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.password_reset_confirm,
{'template_name': 'registration/password_reset_confirm_custom.html'},
name='password_reset_confirm'
),
url(
r'^reset/done/$', auth_views.password_reset_complete,
{'template_name': 'registration/password_reset_done_custom.html'},
name='password_reset_complete'
),
url(
r'^old-admin/lucy_web/package_session_types/(?P<id>d+)/$',
lucy_web_views.package_session_types,
name='package_session_types'
),
url(
r'^old-admin/lucy_web/package_session_types_update/(?P<id>d+)/$',
lucy_web_views.package_session_types_update,
name='package_session_types_update'
),
url(r'^old-admin/', admin.site.urls),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^o/', include('oauth2_provider.urls')),
url(r'^activate/', include('activation.urls')),
url(r'^api/', include('api.urls')),
url(r'^dashboard/', include('dashboard.urls')),
url(r'^', include('lucy_web.urls')),
url(r'^markdownx/', include(markdownx))
]

但是,reverse('dashboard:families')代码中的其他地方工作正常,但只有在这里它才导致错误,所以我认为"问题可能是由循环导入引起的"可能适用于这里。不过,我正在努力弄清楚这可能是什么。

错误堆栈上的重要部分是:

Traceback (most recent call last):
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable

它显示 url 解析器正在尝试迭代,但它正在获取一个对象。因此,您的某些 urls.py 不会将列表或元组作为 urlpatterns 返回。

一种可能的情况是一些只有一种模式的 url模式,您忘记在模式末尾放置逗号:

urlpatterns = (
url(r'^foo/$', my_view_func, name='bar'),
)

如果你忘记了逗号,urlpatterns将是一个正则表达式URLPattern对象,而不是一个正则表达式URLattern列表,就像在你的堆栈上一样得到一个错误。

相关内容

最新更新