{{csrf_token}} gives me 403 Forbidden and {%csrf_token%} gives me 500 Server Error Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of {{csrf_token}} gives me 403 Forbidden and {%csrf_token%} gives me 500 Server Error without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I read these two are basically same thing, but each one gives me different errors I’m not sure which one to go after. I don’t even know how to fix this problem. Can someone please take a look at my code,,I’m struggling with this for two days now.

my html

<div id='notificationsLoader'>
    </div>
<script>
$(document).ready(function(){
  $(".notification-toggle").click(function(e){
    e.preventDefault();
    $.ajax({
      type:"POST",
      url:"{% url 'get_notifications_ajax' %}",
      data: {
        csrfmiddlewaretoken:"{%csrf_token%}",
      },
      success: function(data){
        $("#notificationsLoader").html('<h3>notifications</h3>');
        $(data.notifications).each(function(){
          $("notificationsLoader").append(this + "<br/>")
        })
        console.log(data.notifications);
      },
      error: function(rs, e){
        console.log(rs);
        console.log(e);
      }


    })
  })
})
</script>

the other html

 <li><a class="notification-toggle" href="#">notification</a></li>

and notification is from my python code

@login_required
def get_notifications_ajax(request):
    notification = Notification.objects.get(id=id)
    notes =[]

    for note in notifications:
        notes.append(str(note))
    data={
        "notifications":notes
        }
    json_data = json.dumps(data)
    return HttpResponse(json_data, content_type='application/json')

there’s more to this, but I’ll post just this part because I think the error(both 403 and 500) is saying my server side is wrong

Answer

From Django Project Documenation:

While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many javascript frameworks provide hooks that allow headers to be set on every request.

So you can pass csrftoken value as X-CSRFToken header, it could be fetched from cookie ( i’ve added getCookie function for that needs). You can easily do it by setuping your ajax request with ajaxSetup before sending it, see code below:

// Source https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax    
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

$(".notification-toggle").click(function(e){
  e.preventDefault();
  var token = getCookie('csrftoken');
  $.ajaxSetup({'headers': {'X-CSRFToken': token}});
  // $.ajax... 

Altrnatively you can try to replace your data from:

data: {
        csrfmiddlewaretoken:"{%csrf_token%}",
      },

to

data: {
        csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
      },
We are here to answer your question about {{csrf_token}} gives me 403 Forbidden and {%csrf_token%} gives me 500 Server Error - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji