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
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>
2 Comments
Ryan Shocker
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?
Alessandro Odetti
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.