简体   繁体   中英

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'})

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.

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