【问题标题】:Forbidden (CSRF token missing or incorrect.): /updatecart_index/禁止(CSRF 令牌丢失或不正确。):/updatecart_index/
【发布时间】:2021-02-23 01:35:57
【问题描述】:

在我的 html 中,我有这段代码,用户从数据库中更新数量,为什么我会遇到这种错误 Forbidden (CSRF token missing or incorrect.): /updatecart_index/ ?即使我的表格中有这个{% csrf_token %}

<form method="POST"  id="form"  >{% csrf_token %}
   <input type="hidden" value="{{bought.id}}" name="itemID">
   <input type="submit" value="-" id="down" formaction="/updatecart_index/"  onclick="setQuantity('down');" >
   <input type="text" name="quantity" id="quantity" value="{{bought.quantity}}" onkeyup="multiplyBy()" style="width: 13%; text-align:left;" readonly>
   <input type="submit" value="+" id="up" formaction="/updatecart_index/" onclick="setQuantity('up');" >
 </form>

<script type="text/javascript">
    $(document).ready(function(){
      $("form").submit(function(){
        event.preventDefault();
        var form_id = $('#form')

        $.ajax({
        url: "{% url 'updatecart_index' %}",
        type: 'POST',
        data: form_id.serialize(),
        header: {'X-CSRFToken': '{% csrf_token %}'},
        dataType: "json",
        success: function (response){
            var success = response['success']
            if(success){
                alert("form submittend");
            }else{
                alert("got error");
            }
        },
        failure: function (error){
            alert("Error occured while calling Django view")
        }

    })
      });
    });
</script>

在views.py中

def updatecart_index(request):
    item = request.POST.get("itemID")
    print("dasdasd")
    quantity = request.POST.get("quantity")
    product = CustomerPurchaseOrderDetail.objects.get(id=item)
    print("aa", CustomerPurchaseOrderDetail.objects.get(id=item))
    product.quantity = quantity
    product.save()
    data = {}
    data['success'] = True
    return HttpResponse(json.dumps(data), content_type="application/json")

更新

当我在views.py 中尝试@csrf_exempt 时,request.POST.get("item") 没有从html 中获取数据

【问题讨论】:

  • 我的表单中已经有 {% csrf_token %}
  • @ViaTech 你能发表你的答案吗?

标签: python django ajax


【解决方案1】:

您必须在呈现后从 HTML 中获取 csrf_token。因为 Django 将 {% csrf_token %} 替换为唯一令牌(实际上是 input type="hidden"),所以它是不正确的。你的JS里的token和你form里的token会不一样。

<script type="text/javascript">
  $(document).ready(function () {
    $("form").submit(function () {
      event.preventDefault();
      var form_id = $("#form");
      $.ajaxSetup({
        beforeSend: function (xhr, settings) {
          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"));
          }
        },
      });
      $.ajax({
        url: "{% url 'updatecart_index' %}",
        type: "POST",
        data: form_id.serialize(),
        dataType: "json",
        success: function (response) {
          var success = response["success"];
          if (success) {
            alert("form submittend");
          } else {
            alert("got error");
          }
        },
        failure: function (error) {
          alert("Error occured while calling Django view");
        },
      });
    });
  });
</script>

【讨论】:

  • 什么是 - 列表项?
  • 对不起 - 一些错误。修复它们
  • 好的 - 我现在改变了我的答案。检查this SO 帖子。
  • in my views.py my item = request.POST.get("itemID") 打印无,为什么?
  • 不要使用csrf_exempt。不好的做法。使用我的解决方案。
【解决方案2】:

你可以简单地对你的 Ajax 做这个

<script type="text/javascript">
    $(document).ready(function(){
        $('form').submit(function(){
            event.preventDefault();
            var that = $(this);
            $.ajax({
                url: "{% url 'updatecart_index' %}",
                type: 'POST',
                data: that.serialize()
                ,success: function(data){
                    console.log('Success!');
                }
            });
            return false;
        });
    });
</script>

不要使用csrf_exempt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2021-01-08
    • 2015-10-15
    • 2020-12-24
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多