简体   繁体   中英

Django error “The included URLconf does not appear to have any patterns in it”

I'm trying to write a mixin for a view, SearchFilterMixin , which has a cookie_path class variable:

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'))

In the inheriting view, I'm trying to set cookie_path to a reversed 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')

However, when I try this, my development server crashes with the following error:

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.

Here is the full traceback:

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.

In fact, the same line triggers an error if I even try to reverse that URL in the Django shell:

NoReverseMatch: None is not a registered namespace

Here is again the full traceback:

(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]: 

It seems like I can't use the reversed URL of a certain view as the value of a class variable of that view, correct? If so, how shall I solve this? Should I define self.cookie_path in the __init__() method instead?

Update

Following the comments, here are the contents of 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))
]

However, reverse('dashboard:families') works fine elsewhere in the code, it is only here that it causes the error, so I'm thinking that "the issue is probably caused by a circular import" probably applies here. I'm struggling to get a handle on what that might be, though.

The important part on your error stack is:

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

It shows that the url resolver is trying to iterate but it is getting an object. So some of your urls.py is not returning a list or tuple as urlpatterns.

A possible situation is some urlpatterns with just one pattern where you have forgot to put a comma at the end of the pattern:

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

If you forget the comma, urlpatterns will be a RegexURLPattern object and not a list of RegexURLPattern, getting a error just like on your stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM