【问题标题】:django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.urls' does not appear to have any patterns in itdjango.core.exceptions.ImproperlyConfigured:包含的 URLconf 'api.urls' 似乎没有任何模式
【发布时间】:2020-04-09 04:58:52
【问题描述】:

很难理解我收到此错误的原因。如果我只是离开 api/user/ 路径,它可以正常工作,但是当我尝试添加 api/user/date_counter/ 路径时,我会收到此错误。使用 Django 3。任何帮助将不胜感激。

像下面这样的伪图形是基于 maven 如何显示 dependency:tree 命令的输出。

根据我的经验,它很容易阅读和输入。它自然匹配树状文件结构:

Backend
 |
 +-- api
 |  |
 |  +-- urls.py
 |  |
 |  +-- settings.py
 |    
 +-- date_counter
 |  |  
 |  +-- urls.py
 |    
 +-- user
 |  |  
 |  +-- urls.py    

date_counter/urls.py

from django.urls import path

from date_counter import views

app_name = 'date_counter'

urlpatterns = [
    path('date_counter/', views.DateCounterViewSet.as_view(), name='date_counter'),
]

date_counter/views.py

from django.shortcuts import render
from date_counter.models import Date_Counter
from date_counter.serializers import DateCounterSerializer

class DateCounterViewSet(viewsets.ModelViewSet):
    queryset = Date_Counter.objects.all()
    serializer_class = DateCounterSerializer

date_counter/serializers.py

from date_counter.models import Date_Counter
from rest_framework import serializers

class DateCounterSerializer(serializers.ModelSerializer):
    class meta:
        model = Date_Counter
        fields = ['user', 'date', 'count']

date_counter/models.py

from django.db import models
from user.models import User

class Date_Counter(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField(auto_now=True)
    count = models.IntegerField(default=0)

api/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/user/', include('user.urls')),
    path('api/user/date_counter/', include('date_counter.urls')),
]

用户/urls.py

from django.urls import path
from knox.views import LogoutView
from user import views

app_name = 'user'

urlpatterns = [
    path('register/', views.RegisterUserView.as_view(), name='register'),
    path('login/', views.LoginUserView.as_view(), name='login'),
    path('user/', views.UserView.as_view(), name='user'),
    path('logout/', LogoutView.as_view(), name='knox_logout'),
    path('registersuperuser/', views.RegisterSuperUserView.as_view(), name='register_super_user'),
    path('all/', views.AllUsersView.as_view(), name='all'),
]

api/settings.py

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


SECRET_KEY = 'secret'

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'knox',
    'user',
    'date_counter',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',),
}

ROOT_URLCONF = 'api.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'api.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}



AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

AUTH_USER_MODEL = 'user.User'

堆栈跟踪

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 590, 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 "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in check
    for pattern in self.url_patterns:
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 597, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.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.

【问题讨论】:

  • 粘贴整个 settings.py 和文件夹结构/文件组织
  • 包括所有的settings.py和文件夹结构
  • 你有没有试过把每个网址一一注释掉?

标签: python django django-rest-framework


【解决方案1】:

我认为问题在于您如何将 ViewSet 注册到urlpatterns。试试这样:

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('date_counter', views.DateCounterViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

更多信息可以在documentation找到。

【讨论】:

  • 奇怪的是,我还尝试了使用 generics.ListAPIView 的视图,因为我还认为这可能与 ViewSets 的配置方式有关,但仍然出现错误
  • 正如错误提示的那样,它们是循环导入。请分享您的用户模型和视图
【解决方案2】:

发现问题,date_counter/views.py 文件缺少从 django rest 框架 from rest_framework import viewsets 的导入。

【讨论】:

    猜你喜欢
    • 2019-08-21
    • 2018-06-27
    • 1970-01-01
    • 2022-08-21
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多