tags:

views:

74

answers:

2

I was hoping that Django had a built in way of getting the last url that was visited in the app itself. As I write this I realize that there are some complications in doing something like that (excluding pages that redirect, for example) but i thought I'd give it a shot.

if there isn't a built-in for this, what strategy would you use? I mean other than just storing a url in the session manually and referring to that when redirecting. That would work, of course, but I hate the thought of having to remember to do that for each view. Seems error-prone and not very elegant.

Oh, and I'd rather not depend on server specific referral environment variables.

A: 

you can just write a middleware that does exactly that, no need to repeat logging code on every view function.

Javier
Are you saying there is middleware that does this or that I should create my own middleware for doing this?
Karim
He is saying you should create your own middleware, I believe.
hughdbrown
+3  A: 

No, there is nothing like that built in to Django core (and it's not built in because it isn't a common usage pattern).

Like Javier suggested, you could make some middleware which does what you want. Something like this:

class PreviousURLMiddleware(object):
    def process_response(request, response):
        if response.status_code == 200:
            request.session['previous_url'] = request.get_full_url()
        return response

This middleware would have to go after SessionMiddleware in your settings to ensure that the session will be updated after this (the docs have a pretty picture explaining why this is).

SmileyChris