2

I have a search feature I built for an administrative account in Django on the front-end that queries matched users to the admin with an option to remove them from the database. Currently, they click the button, and they are redirected to the view that handles the backend logic for removing the associated object by the primary key from the database. I am wanting to have the user remove the object on button click and then update the div that the users display in after object has been removed without the page refreshing. How can I go about this?

1 Answer 1

1

Here a super generic example. You can do something like:

in your views.py:

def delete_element(request, element_id):    
    element = get_object_or_404(ElementClass, id=element_id)
    element.delete()
    return HttpResponse("success")

in your urls.py:

url(r'^element_delete/(?P<element_id>\d+)/$', 'app.views.delete_element', name="name_element_delete"),

in your template:

<script>

$(".delete-button").click(function(){
    var element =  this;
    var url = $(this).data('url');
    $.ajax({
                type: 'GET',
                url: url,            
                success: function(){               
                // do what you want with 'element' var
                },
                error: function(){
                    alert("Error on delete, please try again");
                },
    });
});

</script>
Sign up to request clarification or add additional context in comments.

2 Comments

So, IMO, when I look at this it's an AJAX call that requests the view to delete, but how would I technically go about removing the div element from the page? Would I do some hack-ish javascript to remove the element that matches with the ID of the object using template tags or something?
If you want to delete the button element, for example, you can do $(element).remove(); on the sucesss, for any other element in the page ou can do $("#element-id").remove() or $("#element-id").hide() if eventually you want to show it again later.

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.