0
我有視圖編輯用戶配置文件使用Ajax,我檢查請求類型,如果後剛剛獲得JSON數據與request.body。但Django給我一個錯誤:'從請求的數據流中讀取後無法訪問主體'。顯然我只能訪問一個請求數據,所以如何在閱讀正文之前檢查請求類型。這裏被簡化代碼Django的無法訪問請求多次
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')
完整的錯誤信息:
Internal Server Error: /accounts/edit_profile/
Traceback (most recent call last):
File "/home/void/Projects/workspace/venv/lib/python3.4/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/home/void/Projects/workspace/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/void/Projects/workspace/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/void/Projects/workspace/workspace/accounts/views.py", line 79, in edit_profile
req_str = request.body.decode('utf-8')
File "/home/void/Projects/workspace/venv/lib/python3.4/site-packages/django/http/request.py", line 264, in body
raise RawPostDataException("You cannot access body after reading from request's data stream")
django.http.request.RawPostDataException: You cannot access body after reading from request's data stream
該代碼甚至不工作(你是指不同的變量行3和4),但如果它沒有,它不會因爲你要求的錯誤:檢查請求的方法不「讀」的要求。請顯示您使用的*實際*代碼和您得到的完整錯誤。 –
完整的錯誤和追溯在哪裏? –
可疑的是,這個異常應該已被視圖中的'Exception Exception'行捕獲。不過,您是否有任何可能會干擾的自定義中間件? –