Django 运行报异常:AttributeError: 'str' object has no attribute 'get'

2022-11-12,,,,

Technorati Tags: Python,Django,Web

在使用django.contrib.auth用户机制进行用户的验证、登录、注销操作时,遇到这个异常

首先是写了一个登录的视图,要求如果用户登录成功,则页面跳转到用户主页(home):

from django.shortcuts import redirect
from django.template.loader import get_template
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages def user_login(request): if request.method == 'POST':
loginForm = login_form.LoginForm(request.POST)
if loginForm.is_valid():
login_name = request.POST['username'].strip()
login_password = request.POST['password']
user = authenticate(request, username=login_name, password=login_password)
if user is not None:
if user.is_active:
login(request, user=user)
return '/home/'
else:
messages.error(request, '用户已被禁用。请联系网站管理员')
else:
messages.error(request, '用户不存在。')
else:
messages.error(request, '请检查输入的用户名和密码') else:
loginForm = login_form.LoginForm() template = get_template('login.html')
html = template.render(locals(), request) return HttpResponse(html)

运行后,当输入用户名和密码后,点击“登录”时,报如下错误:

Internal Server Error: /
Traceback (most recent call last):
File "d:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "d:\ProgramData\Anaconda3\lib\site-packages\django\utils\deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "d:\ProgramData\Anaconda3\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'str' object has no attribute 'get'
[15/Nov/2020 23:07:06] "POST / HTTP/1.1" 500 69094

之前没有使用Django的认证机制,程序运行正常,怎么使用了反倒报错了呢。网上找了很久,也没有对应的异常和解决方案。

终于,不经意间,发现了一行代码,第19行:return '/home/',本意是跳转到用户的主页,但这个写法是错误的,应该是:

return redirect('/home'/)

修改之后,正常运行没有报异常,页面也可以跳转到预期的用户主页。

另外,推荐一篇文章:django从请求到响应的过程,文章很详细地讲解了Django的运行原理。

Django 运行报异常:AttributeError: 'str' object has no attribute 'get'的相关教程结束。

《Django 运行报异常:AttributeError: 'str' object has no attribute 'get'.doc》

下载本文的Word格式文档,以方便收藏与打印。