我有用ajax编辑用户配置文件的视图,我正在检查请求类型,如果它的post只是获取Json数据请求.正文. 但Django给了我一个错误:“在读取请求的数据流之后,您无法访问body”。显然我只能访问一个请求数据,那么在读取正文之前如何检查请求类型。这是简化代码
def edit_profile(request):
if request.method == 'POST':
name = ''
email = ''
bio = ''
user_profile = User.objects.get(username=request.user.username)
try:
req_str = request.body.decode('utf-8')
req_json = json.loads(req_str)
name = req_json['username']
email = req_json['email']
bio = req_json['bio']
if name:
user_profile.username = name
if email:
user_profile.email = email
if bio:
user_profile.account.bio = bio
user_profile.save()
user_profile.account.save()
except KeyError:
print("can't parse json")
except Exception as e:
print('fialed to proccess request', e)
return JsonResponse({
'username': user_profile.username,
'email': user_profile.email,
'bio': user_profile.account.bio
})
else:
return HttpResponse('nothing changed')
完整错误消息:
^{pr2}$
您的中间件必须正在访问
request.body
,这可能会导致错误,请检查您的MIDDLEWARE_CLASSES
中是否有任何可能正在访问数据的自定义/中间件。检查您在中间件中使用的模块/应用程序中是否有此错误。在这里有一些很好的解释。https://stackoverflow.com/a/28641930/3448851
相关问题 更多 >
编程相关推荐