5

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)
patrick
  • 185
  • 2
  • 7
  • 1
    there is no code in here, it's hard to have an idea of what you're doing – Andrea Giammarchi Jul 22 '20 at 14:34
  • Hi Patrick, welcome to Stackoverflow! To make it easier for other users to help you with your issue it's recommended that you share a few snippets of the code you're using, so that they can try to replicate the issue as well :) – Gabcvit Jul 22 '20 at 14:39
  • Sorry about that, I just added some code – patrick Jul 22 '20 at 15:00

2 Answers2

3

First of all to get the csrf you can use the following code

Get code from this link clickme1

now that we got the csrf , add this line of code into you headers of fetch

'X-CSRFToken':csrftoken,

Farhan Syedain
  • 408
  • 3
  • 12
1

First, from Andrea and Gabcvit, some pieces of code will be greatly appreciated.

Editing Farhan's answer: you need to manually retrieve the csrf token as there isn't a default in javascript for you to do so. You can do this by:

import jQuery from 'jquery';  // important dependency

function getCookie(name) {
  let cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    let cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      let cookie = jQuery.trim(cookies[i]);
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
      }
    }
  }
  return cookieValue;
}

var csrftoken = getCookie('csrftoken');

In case that React didn't receive Django's csrf token (which happened in my case), you need to add the following code above your view:

@method_decorator(ensure_csrf_cookie, name='dispatch')
class UserLoginView(View):
    # ...

In case you need more help, this MDN article will help you.

crimsonpython24
  • 2,223
  • 2
  • 11
  • 27