简体   繁体   中英

Why am I getting a 403 Forbidden error in Django when I do a POST request with AJAX?

In Django Console I'm getting this message in red:

[16/Jan/2015 01:33:34] "POST /accounts/benjamin/listview HTTP/1.1" 404 7562

In Chrome Dev Console, I'm getting this error:

jquery-2.1.1.min.js:4 POST http://127.0.0.1:8000/accounts/benjamin/listview/ 403 (FORBIDDEN)

jquery-2.1.1.min.js:4 k.cors.a.crossDomain.send

Here is my view method: (note, I just now added @ensure_csrf_cookie after reading other SO posts, but this did not resolve the issue)

@ensure_csrf_cookie
def delete_object(request):
    if request.is_ajax():
        print "request is ajax"
        object_name = request.POST.get('entryname')
        targetobject = Entry.objects.get(headline=object_name)
        if request.user.username == targetobject.author:
            targetobject.delete()
            print "hello" 
        return HttpResponseRedirect('/storefront/')

And AJAX code in the template:

<script type="text/javascript">
    var my_app = {
      username: "{{ request.user.username }}"  
    };
</script>

<script>
 $(document).ready(function() {
    $(".delete_button").click(function() {
        var id = $(this).attr('id');
        $.ajax({
            type: "POST",
            url: "/accounts/" + my_app.username + "/listview/",
            data: { entryname:id },
            success: function(response){
                alert(response.success);
            }
        });
        return false;
    });
});
</script>

将csrf令牌添加到您的ajax请求中

csrfmiddlewaretoken: '{{ csrf_token }}'

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