1

I must delete record from Django db use Jquery/Ajax. Can you help me?

django /views function

def owner(request, identifer):
    x = get_object_or_404()
    if request.method == "DELETE":
        x.objects.delete()

ajax code here:

 $(document).ready(function() {
       $(".delete").click(function(){
            var id_number = this.id;
            alert(id_number);
            $.ajax({
               type: 'DELETE',
               url: 'owner/{item.id}/',
               data: 'identifer='+id_number,
               success: function(){
                  if(data) {alert("Success!")}
            });
         });
  });
2
  • so what is the problem now? Commented Jun 29, 2017 at 7:38
  • Your code is not clear. You want to delete object on the basis of item.id or id_number? Give some more detail of your code. Commented Jun 29, 2017 at 10:18

2 Answers 2

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!");
                }
            });

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

Comments

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 %}"

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.