简体   繁体   中英

forbidden 403 error in 'PUT' request Ajax in django rest framwork

I am using django-rest framework while sending put ajax request got error 403 forbidden.

user-details.html

   <form action="{% url 'user-detail' pk=object.pk %}" id="use1">
        {% csrf_token %}
        {% for key,value in serializer.items %}
             {{key}} <input value="{{value}}" type="text" class="form-control" /><br>
        {% endfor %}

        <button class="btn btn-warning edit_record" type="button" >Update</button>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button>
    </form>

when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here.

As far as I know we get this error when csrftoken is missing but I have csrf_token in my form.

$(".edit_record").on("click",function() {
        var url = document.location.pathname
        form = $(this).closest("form")[0],
        formData = new FormData(form);
         $.ajax({
             type:'PUT',
             url: url,
             data: formData,
             success: function (data) {

            },
              headers: {'X_METHODOVERRIDE': 'PUT'},

         });
    });

I used ModelViewset in views.py

 class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserProfileSerializer

        def update(self, request, *args, **kwargs): 
            import pdb;pdb.set_trace() 
            response = super(UserViewSet, self).update(request, *args, **kwargs)
            success =  True if response.status_code in [200,201] else False
            return Response({'object':response.data, 'success':success})

        def partial_update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()

        def destroy(self, request,*args, **kwargs):   
            response = super(UserViewSet, self).destroy(request, *args, **kwargs)
            success =  True if response.status_code == 204 else False
            return Response({'data':success})

I think It is a Problem with Django Security and your Cookies. You need to configure your Middleware. Please take a look at this SO solution and this piece of Django Documentation .

What you could try is adding this to your Ajax Call and I would change the type to POST instead of PUT.

$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
  type: "POST",
  ..... 
 });

What worked for me is implementing this into my JS:

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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
   return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
       if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
           xhr.setRequestHeader("X-CSRFToken", csrftoken);
     }
  }
});

try this,

    $.ajax({
        type:"DELETE",
        data:{},
        url:"{{ category_update }}",
        beforeSend:function(xhr){
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        },
        success:function(data,textStatus){
            location.replace(location.href);
        },
        error:function(XMLHttpRequest, textStatus, errorThrown){
           document.write(XMLHttpRequest.responseText);
        }
    });

the point is :

beforeSend:function(xhr){
     xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
},

Thank you all for helping me but I got the solution by debug the dispatch method.Here I found that form data is missing that means there is invalid formdata in request. There is no issue of csrf_token but issue in parameters which sent to ajax request.

In ajax currently i used -

    form = $(this).closest("form")[0],
    formData = new FormData(form);

and send this formData in request( still now i Don't know why it is not working here while i always used this thing in django).I just replace the above code with following code.

   form = $(this).closest("form"),            
   formData  = form.serialize()

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