I'm trying to send a JSON request to my Django application with a csrf token, but I can't figure out how. I've gotten the token into a variable that I can reference, but I don't know how to send it through the JSON request with fetch. I've added 'csrfmiddlewaretoken': csrftoken
into the JSON.stringify part of body, but I'm still getting an error saying 403 Forbidden. Can someone please help me with this? Thank you! (sorry for the weird indentation on the code)
Javascript file:
fetch('/update', {
method: 'PUT',
body: JSON.stringify({
'csrfmiddlewaretoken': csrftoken,
'liked': true,
'post_id': parseInt(button.dataset.post_id)
})
})
views.py:
data = json.loads(request.body)
try:
content = data.get('content')
except:
JsonResponse({'error': 'content required'}, status=400)
try:
id = data.get('id')
post = Post.objects.get(id=id)
except:
JsonResponse({'error': 'post not found'}, status=400)
if request.user == post.user:
post.content = content
post.save()
return JsonResponse({'message': f'received: {content}'})
return JsonResponse({'error': "can't edit this user's posts"}, status=403)