我收到类型错误,显示"不是JSON可序列化的#34;。 添加会话相关代码后,会出现此错误。
views.py
def jlogin(request):
if request.method == 'POST':
username = request.POST['uname']
password = request.POST['pword']
user = authenticate(username=username, password=password)
if user is not None:
login(request,user)
print(user)
request.session['user']=user
return redirect('/feeds/')
else:
return render(request,'join/login.html')
else:
user = request.session.get('user')
print(user)
if user is None:
return render(request,'join/login.html')
else:
return render(request,'feeds/feeds.html')
login.html
<!DOCTYPE html>
<html>
<head>
<title>Login to dEEPsIGMA</title>
</head>
<body>
<form action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
Username :
<input type="text" name="uname"/> <br>
Password :
<input type="text" name ="pword"/>
<input type="submit">
</form>
</body>
</html>
回溯:
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\core\handlers\base.py" in get_response
207. response = middleware_method(request, response)
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\contrib\sessions\middleware.py" in process_response
49. request.session.save()
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\contrib\sessions\backends\db.py" in save
58. session_data=self.encode(self._get_session(no_load=must_create)),
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\contrib\sessions\backends\base.py" in encode
89. serialized = self.serializer().dumps(session_dict)
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\core\signing.py" in dumps
89. return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "C:\Python27\lib\json\__init__.py" in dumps
250. sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\lib\json\encoder.py" in encode
207. chunks = self.iterencode(o, _one_shot=True)
File "C:\Python27\lib\json\encoder.py" in iterencode
270. return _iterencode(o, 0)
File "C:\Python27\lib\json\encoder.py" in default
184. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /
Exception Value: <User: user1> is not JSON serializable
请帮助解决此错误。解释发生此错误的原因。
答案 0 :(得分:6)
产生错误的行是:
request.session['user']=user
Django在版本1.6之后一直使用JSON来序列化会话数据。关于Django documentation的更多信息。用户对象不是JSON可序列化的。因此,您需要确保存储在会话变量中的对象应该是JSON可序列化的。在Django 1.6之前,Django使用的序列化程序是PickleSerializer,你的代码可以完美运行。
要使代码正常工作,您可以执行以下操作之一: