QueryDict对象没有属性会话Django

时间:2020-11-10 10:17:04

标签: python django session python-requests

所以我基本上有一个这样定义的登录表单:

def login_request(request):
    if request.method == 'POST':
        data = request.POST
        auth_backend = AuthenticationBackend()
        login_form = LoginForm(data)
        if login_form.is_valid():
            user = auth_backend.authenticate(data, password=data['password'], email=data['email'])
            if user:
                login(data, user)
                # redirect to homepage
            else:
                login_form.add_error('password', "Password doesn't match email")
    else:
        data = {}
        login_form = LoginForm()
    return render(request, 'login.html', {'form': login_form, 'data': data})

如果给定条件匹配,则用户必须登录。但是,当我这样做时

login(data, user)

我收到此错误:

Internal Server Error: /users/login/
Traceback (most recent call last):
  File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\users\views.py", line 34, in login_request
    login(data, user)
  File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\contrib\auth\__init__.py", line 99, in login
    if SESSION_KEY in request.session:
AttributeError: 'QueryDict' object has no attribute 'session'

为什么会这样?我怎样才能解决这个问题?请帮助我,在此先感谢! 中间件:


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',
]

1 个答案:

答案 0 :(得分:1)

尝试更改此内容:

if user:
    login(data, user)

做到:

if user:
    login(request, user)