在Django POST请求中,禁用的CSRF令牌丢失或不正确,即使我在表单中有csrf令牌

时间:2018-02-13 07:19:21

标签: javascript python ajax django

我在制作AJAX请求时在数据中包含了csrf_token。但是当我发出POST请求时,我一直收到403作为回复。

在发出请求之前,我检查了csrf_token是否为空。

一切似乎都很好,可能会引发错误?

这是我的HTML代码:

<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代码:

       $("#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代码:

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)

我的应用的urls.py中的代码:

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'), 

]

1 个答案:

答案 0 :(得分:1)

通过在脚本上添加以下代码来尝试相同的操作

$.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'));
            }
        }
    }
});