0

I am trying to send a 'POST' request from AJAX with fetch to a Django view with a @csfr_exemptdecorator 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)

1 Answers1

0

Try with class base view.

 from django.utils.decorators import method_decorator

 @method_decorator(csrf_exempt, name='dispatch')
 class Follow(View):

    def post(self, request):
        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)

OR

 class Follow(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(Follow, self).dispatch(request, *args, **kwargs)
    def post(self, request):
        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)

urls.py:

path('follow/', Follow.as_view(), name='follow'),
Pradip Kachhadiya
  • 2,067
  • 10
  • 28