[Answered ]-Delete record in Django db with ajax

2👍

You must defind you type of data

    <script>
        function deleteCommand(svCommandId) {
            var url = $('#service_command_form').attr('action') + svCommandId;
            $.ajax({
                url: url,
                type: "DELETE",
                dataType: "json",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
                },
                success: function () {
                    $('#service_command_' + svCommandId).remove();
                    addMessage("Deleted data successfully");
                },
                error: function () {
                    addMessage("Delete failed!");
                }
            });
👤Viktor

0👍

You didn’t explain what went wrong, but if I look into your code it seems you need to change you view code:

def owner(request, identifer):

    try:
        x = <YourModelName>.objects.get(id=identifier)

    except <YourModelName>.DoesNotExist:

        return error message here ...

    x.delete()

    return success message here ...

There is also an error in your JS code, you didn’t use double brackets:

url: "owner/{{item.id}}/"

But even better you shouldn’t hardcode your url, it’s better to use the {% url %} template tag

url: "{% url 'name-of-owner-view' item.id %}"

Leave a comment