I have a JavaScript fetch to call a URL to pass data into my Django view to update a value for the user.
Error in views.py:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\rossw\Documents\Projects\Scry\apps\administration\views.py", line 47, in administration_users_page
switchData = json.load(request)['switch']
File "C:\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Error in browser:
0
PUT http://127.0.0.1:8000/administration/users/JM/ 500 (Internal Server Error)
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
JavaScript:
const changeAdminUserAction = (id,data) => {
console.log(data)
fetch(`/administration/users/${id}/`,{
method: 'PUT',
body: JSON.stringify({type: "adminUser", switch: data}),
headers: {'X-CSRFToken' : csrfToken, 'Content-Type': 'application/json'},
})
.then((response) => response.json())
.then((result) => {location.reload()})
.catch((err) => {console.log(err)})
}
views.py:
if request.method == 'PUT':
user = CustomUser.objects.get(username=kwargs.get('username'))
switchType = json.load(request)['type']
switchData = json.load(request)['switch']
print(switchType, switchData)
if switchType == 'adminUser':
user.admin_user = switchData
elif switchType == 'admindata':
user.admin_data = switchData
elif switchType == 'Status':
if user.status == COMMON.USER_ACTIVE:
user.status = COMMON.USER_SUSPENDED
else:
user.status = COMMON.USER_ACTIVE
user.failed_logins = 0
user.save()
return JsonResponse({})
This is throwing an error at switchData = json.load(request)['switch']
. I don't know why it is throwing the error there as the previous line switchType = json.load(request)['type']
works as expected and returns the value that was passed to it.
data
is a integer - either 1 or 0. I have tried make this value a string but it throws the same error.