简体   繁体   中英

Forbidden (CSRF token missing or incorrect.): /updatecart_index/

in my html i have this code where the user updating the quantity from the database,why i am encounter this kind of error Forbidden (CSRF token missing or incorrect.): /updatecart_index/ ? eventhought i have this in my form {% 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>

in 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")

UPDATE

when i tried @csrf_exempt in views.py, the request.POST.get("item") didnt get the data from the html

You must get the csrf_token from the HTML - after it's rendered. Because Django replaces {% csrf_token %} with a unique token ( input type="hidden" , actually), so it'll be incorrect. The token in your JS and the token in your form will be different.

<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>

You can simply do this to you 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>

and dont use csrf_exempt

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