Sander van Leeuwen
Sander van Leeuwen

Reputation: 3033

Django saving HTTP_REFERER to use it as landingpage information

I would like to know if there is a better solution for this.

The website I'm building has some forms which need information about the page the user started his 'journy'. Right now I'm saving HTTP_REFERER to the session and use it later on. A disadvantage is the need for set_expiry(0) which clears the session on browser close. I like the behavior that users don't need to login every time they close the browser.

I wrote a little middleware class that looks like this:

class RefererMiddleware(object):
    def process_response(self, request, response):
        try:
            if not request.session.get('http_landingpage'):
                request.session['http_landingpage'] = request.META.get('HTTP_REFERER')
                request.session.set_expiry(0)
        except Exception:
            pass
        return response

Any suggestions for improvement? Other solutions?

Upvotes: 2

Views: 946

Answers (1)

Mariusz Jamro
Mariusz Jamro

Reputation: 31643

What about setting a cookie, which will expire when the browser is closed. You can do it in the middleware and in the end the session will be left intact.

#Usage: response.set_cookie( 'cookie_name', 'cookie_value' )

class RefererMiddleware(object):
    def process_response(self, request, response):
        if not request.COOKIES.has_key( 'HTTP_REFERER' ):
            response.set_cookie( 'HTTP_REFERER', request.META.get('HTTP_REFERER') )
        return response

Upvotes: 1

Related Questions