i have view for editing user profile with ajax, i'm checking the request type, if its post just get Json data with request.body. but Django is giving me an error: 'You cannot access body after reading from request's data stream'. apparently i can only access request data one, so how do i check request type before reading the body. here is simplified code
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')
full error message:
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