[Fixed]-How to save the latest url requests in django?

1👍

Hmm, don’t know if I would do it with middleware, or right a decorator. But as your question is about Middleware, here my example:

class ViewLoggerMiddleware(object):
    def process_response(self, request, response):
        # We only want to save successful responses
        if response.status_code not in [200, 302]:
            return response

        ViewLogger.objects.create(user_id=request.user.id, 
            view_url=request.get_full_path(), timestamp=timezone.now())

Showing Top 5 would be something like;

ViewLogger.objects.filter(user_id=request.user.id).order_by("-timestamp")[:5]

Note: Code is not tested, I’m not sure if status_code is a real attribute of response. Also, you could change your list of valid status codes.

Leave a comment