0

I have create a delete function on Django when i try to delete a post using jQuery I am getting this error Field 'id' expected a number but got \n \n \n I also add try to assign id over the pk but I am getting the same error can anybody tell me how can I use this function using jQuery

def ArticleDelete(request):
    if request.method == "POST":
        pk = request.POST.get('pk')
        article = get_object_or_404(Article, pk=pk)
        messages.success(request, 'The story was deleted successfully!')
        article.delete()
        return JsonResponse({"success": True}, status=200)
    else:
        return JsonResponse({"success": False}, status=400)

urls.py

urlpatterns = [
    path('delete/', views.ArticleDelete, name='delete'),
}

index.js

$('.delete').click(function () {
        var this_html = $(this);
        var pk = this_html.parent().parent().children().first().text();

        $.ajax({
            url: '{% url "del" %}',
            type: 'POST',
            headers: { "X-CSRFToken": '{{csrf_token}}' },
            data: { pk: pk },
            success: function () {
                this_html.parent().parent().remove();
            }
        });
    })
1
  • 1
    the problem seems from var pk , show your template file. also, console.log(pk) may help you debug. Commented Dec 3, 2020 at 20:56

1 Answer 1

1

Add something to print out the value of pk from your request.POST (to make sure it is what you think)

pk = request.POST.get('pk')
print('pk from POST = ', pk)

You could also try forcing pk to a known value in your ArticleDelete function to isolate whether the problem is coming from iffy data in the request.POST or something else within the ArticleDelete function

Oh wait - it looks like you've got a type mismatch now that I look again. Try casting your pk from the POST to an int, so...

if request.method == "POST":
    pk = int(request.POST.get('pk'))  # Make it an int before passing to query
    article = get_object_or_404(Article, pk=pk)
    ...

Right now it's being returned as a string, which the database doesn't seem to like - it looks like it wants an integer value instead

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.