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