简体   繁体   中英

Forbidden CSRF token missing or incorrect in Django POST request even though I have csrf token in form

I have included csrf_token in data while making AJAX request. But I keep getting 403 as a response when I make a POST request.

I checked whether csrf_token is empty or not before making the request.

Everything seems fine, what could be triggering the error?

Here is my html code:

<form  method = "POST" >
{% csrf_token %}

<div class="form-group">
  <label for="name">Name:</label>
  <input type="text" class="form-control" id="name" placeholder="Enter name" name="name" required>
</div>

<div class="form-group">
  <label for="email">Email:</label>
  <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" >
</div>

<div class="form-group">
  <label for="pwd">Password:</label>
  <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" >
</div>

<div class="form-group">
  <label for="name">Website:</label>
  <input type="text" class="form-control" id="website" placeholder="Enter website" name="website">
</div>

<div class="checkbox">
  <label><input type="checkbox" name="remember"> Remember me</label>
</div>

<input type="text" id="submit" class="btn btn-default" value="Submit">

Javascript Code:

       $("#submit").click(function(){


           var finalData = {};
           finalData.name = $('#name').val();
           finalData.email = $('#email').val();
           finalData.pwd = $('#pwd').val();
           finalData.website = $('#website').val();
           finalData.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();


           $.ajax({

                  url: window.location.pathname,
                  type: "POST",
                  data: JSON.stringify(finalData),
                  contentType: "application/json",

                  success: function(data){

                        alert('Yo man');
                  },

                  error: function(xhr, status, error) {
                      alert(xhr.responseText);
                  }


                });

    });

Python code:

def signup(request):

if request.method == 'POST':
   response_json = request.POST
   response_json = json.dumps(response_json)
   xy = json.loads(response_json)

   user = User()
   user.name = xy['name']
   user.email = xy['email']
   user.password = make_password(xy['pwd'])
   user.website = xy['website']
   user.save()

   return JsonResponse({'name': 'test'}, status=200)


else:
    context = {'dummy': 'dummy'}
    return render(request, 'forms/signup.html', context)

Code in urls.py of my App:

from django.conf.urls import url
from . import views

urlpatterns = [

# HomePage
url(r'^$', views.index, name='index'),

# Signup Page
url('signup', views.signup, name='signup'), 

]

Try the same by adding following code on top of your script

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (settings.type == 'POST' || settings.type == 'PUT' || settings.type == 'DELETE') {
            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;
            }
            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                // Only send the token to relative URLs i.e. locally.
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            }
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM