Recently Viewed URL, Ideas?

Hi, I am working on getting the user’s last five visited URL pages and storing them in sessions in the DB. This is what I have so far. Curious if anyone has other ideas on how to do this:

class LastVisitedMiddleware(object):
    """Set the five last visited url's as session field's, to later display in a recently viewed box."""
    def process_request(self, request):
        """Intercept the request and add the current path to it"""
        request_path = request.get_full_path()
        try:
            """If less than six session are stored add a new session url"""
            if request.session['currently_visiting'] < 5:
                request.session['last_visited'] = request.session['currently_visiting']
            else: 
                """Deleted oldest session key and add the newest"""
                del request.session['last_visited'][5]
                request.session['last_visited'] = request.session['currently_visiting']
        except KeyError:
            # silence the exception - this is the users first request
            pass
        request.session['currently_visiting'] = request_path

This may or may not be satisfactory for your purposes - it depends upon how much AJAX is being used in your system. (An AJAX request is a URL being accessed, but isn’t a “page” being requested.)

Note: Your syntax for appending items to your list isn’t correct - this code isn’t going to do what you want it to do. Depending upon the order you want the items in the list, you’ll want to add the current url to the list and only keep the 5 you want kept.

1 Like

Solved using sessions instead.