TypeError:__ init __()缺少1个必需的位置参数:'get_response'

时间:2017-09-21 23:13:48

标签: python django

当我运行我的服务器python3 manage.py runserver时 浏览器返回A server error occurred. Please contact the administrator. 然后我得到这个错误

`Traceback (most recent call last):
  File "/usr/lib/python3.5/wsgiref/handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 170, in __call__
    self.load_middleware()
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 52, in load_middleware
    mw_instance = mw_class()
TypeError: __init__() missing 1 required positional argument: 'get_response'

我的设置文件就是那样

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
]

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

并且在may项目中我创建了middleware.py,它看起来像这样

from django.conf import settings

class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

这么有想法?!

3 个答案:

答案 0 :(得分:3)

您的中间件是一种新型中间件,因此您应该在设置中使用MIDDLEWARE而不是MIDDLEWARE_CLASSES

答案 1 :(得分:2)

现在我解决了我的错误。我将django版本从django 1.8更新为django 1.11,

test_string <- c('1234','5678','', 'Help me Stack Overflow') charToInt64(test_string) # returns int64 [1] 1234 5678 <NA> <NA> with warning charToInt64(head(test_string,-1)) # returns int64 [1] 1234 5678 <NA> without warning

并在settings.py

中将sudo pip install django==1.11更改为MIDDLEWARE_CLASS

然后迁移数据库

MIDDLEWARE

它运作良好

答案 2 :(得分:0)

当您实例化类时,需要输入get_response作为参数,因为您的类会自动运行其 init ()方法。 所以:

newinstance = LoginRequiredMiddleware(response)

如果您将括号留空,则init缺少您设置的参数。