0

In my django application, when I visit a particular URL ex:enter_database, a view function is called that adds database entries. Now when I visit a different URL, I want to clear the database entries. My question, is it possible to call a method while leaving a view/URL.

Note: I can clear the entries by adding the logic in every other view, which is not the approach I want to do. I am looking for a way to call a method while exiting the current displayed view.

Surya Tej
  • 1,342
  • 2
  • 15
  • 25

1 Answers1

0

In the end of your view you have to create response object and return it.

So I don't know is a correct Django way or not, but you can create custom reponse class and insert logic inside here

class HttpResponseWithDataClearing(HttpResponse):
    def __init__(self, content=b'', *args, **kwargs):
        
        # Some custom logic here (clear the entries?)
        
        super().__init__(content, *args, **kwargs)

After that change view's return statement

return HttpResponse(...)
↓
return HttpResponseWithDataClearing(...)

Where you want to add custom logic.

If you want to add logic when already response sent and you moving to another page, that is impossible to do at backend.

You must to set javascript action on page leaving. And do ajax request to data_clear_url

window.onunload = function() {
    do_ajax_request("data_clear_url");
}
  • EDIT1: onunload method not working

I tried to reproduce javascript onunload method and looks like ajax request is not properly working with Chrome in this case. You can check this article

rzlvmp
  • 7,512
  • 5
  • 16
  • 45