Search code examples
djangodjango-sessions

Django clear request session value if user navigates away from certain pages


I need to clear request session variable each time user navigates from certain pages.

I was thinking writing my own middleware for such thing and to implement process_request to clear the variable when needed.

what do you think?

do you know better solution?

would it damage performance instantly?

10x


Solution

  • 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.