Django:ImportError“看起来不像模块路径

时间:2019-08-22 23:00:53

标签: python django

我刚开始学习Django,并尝试向我的应用程序添加中间件。

在ProjectFolder / app下,我具有以下文件:

  1. 一个空的__init__.py文件
  2. settings.py文件-该文件的内容是默认内容,除了:
  MIDDLEWARE = (
     'SimpleMiddleware',
     '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',
 )
  1. SimpleMiddleware.py文件:
class SimpleMiddleware(MiddlewareMixin):

    def __init__(self, get_response):
        print("***********************************SIMPLE MIDDLEWARE")
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        print("***********************************SIMPLE MIDDLEWARE")
        response = self.get_response(request)
        # Code to be executed for each request/response after
        # the view is called.
        return response

    def process_request(self, request):
        print("***********************************SIMPLE MIDDLEWARE")
        return None
  1. url.py文件:
    from app import views

    urlpatterns = [
        path('hello', views.index, name='index'),
        path('core', include('core.urls')),
    ]

但是,当我通过命令“ python manage.py runserver”运行应用程序时,出现错误:

  

ImportError:SimpleMiddleware看起来不像模块路径

您知道我在做什么错吗?

如果您想查看完整的代码,请单击此处: https://bitbucket.org/MATAN_BL/djangotry/src/master/app/

1 个答案:

答案 0 :(得分:1)

您需要中间件的完整路径,并假设您给出的结构很可能是app.SimpleMiddleware.SimpleMiddleware

MIDDLEWARE = (
     'app.SimpleMiddleware.SimpleMiddleware',
     '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',
 )