I am trying to send a 'POST' request from AJAX with fetch
to a Django view with a @csfr_exempt
decorator and I still get a 403 Forbidden (CSRF token missing or incorrect.): /profile/follow
error. Can someone explain why? (Newbie here).
This is the .js
:
function follow_user(user, follower, action) {
fetch(`follow`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user: user,
follower: follower,
action: action
})
})
.then(response => response.json())
.then(data => {
document.querySelector("#followers-count").innerHTML = `Followers: ${data.followers}`
});
console.log(console.log(`Schiscia: ${follower} ${action} ${user} ${data.followers}`));
and the view is:
@csrf_exempt
def follow(request):
if request.method == "POST":
user = request.POST.get('user')
follower = request.POST.get('follow')
action = request.POST.get('action')
target = User.objects.get(username=user)
sourceusr = User.objects.get(username=follower)
if action == 'follow':
target.followers.append(sourceusr)
sourceusr.following.append(target)
return JsonResponse({'Following': target.following}, safe=False,
status=201)