You can use the request_finished
signal to detect an HTTP request and trigger a function to get the current page's path to check if the user has navigated to a different page. If they have, then you can call flush()
on the session, or set a specific session var to nil, etc.
Something like:
from django.core.signals import request_finished
def check_url(request):
original_path = '/path_to_original_page'
if HttpRequest.get_full_path(request) != original_path:
request.session.flush()
request_finshed.connect(check_url, sender)
Take a look at the docs on Signals and Sessions for more information. I don't think writing your own middleware for this is necessary, but choose whatever suits your needs.