I.Jokhadze I.Jokhadze - 2 months ago 20
Ajax Question

jquery 500 (Internal Server Error)

I keep getting a 500 server response, it sends item_id but can't load function, so i can't get resp status and message.

var remove_item_request = function(item_id){
$.post(
'/remove/item/',
{
item_id:item_id,
},
function(resp){
console.log(resp)
if(resp.status==200){
alert('Removed!!');
document.location = 'buy-requests/show/';
}
else{
alert(resp.message);

}
}
);


}


and here is my view.py:

def remove_item(request):
if request.method == "POST":
item_id = int(request.POST.get('item_id', None))

if item_id is None:
return HttpResponse(status=400)
else:
a = CartItem.objects.filter(id=item_id).delete()
a.save()
return JsonResponse({'status': 200, 'message': 'item Removed'})
else:
return JsonResponse({'status': 400, 'message': 'invalid request type'})

Answer

You're getting the 500 error because of a.save().

CartItem.objects.filter(id=item_id).delete() returns a tuple as per the docs -

The delete method, conveniently, is named delete(). This method immediately deletes the object and returns the number of objects deleted and a dictionary with the number of deletions per object type

>>> e.delete() # from the docs
(1, {'weblog.Entry': 1})

So you cannot call save on that.

An alternate implementation would be

def remove_item(request):
    if request.method != "POST":
        return JsonResponse({'status': 400, 'message': 'invalid request type'})

    item_id = int(request.POST.get('item_id', None))
    if item_id is None:
        return HttpResponse(status=400)

    # get the item out
    item = CartItem.objects.filter(id=item_id).first()
    if item is None:
        # it does not exist ? return the same status code
        return HttpResponse(status=400)

    item.delete()
    # if you really want to cross check
    # num_deletes, num_deletes_per_object_type = item.delete()
    # num_deletes should be greater than zero, and in your case == 1
    return JsonResponse({'status': 200, 'message': 'item removed'})

If the id is unique, then you can use CartItem.objects.get - if not found, it raises a CartItem.DoesNotExist exception.