I know using referrer = self.request.META.get('HTTP_REFERER')
I can find the previous page referrer link but I need to go one step further back, something like: referrer = self.request.META.get('HTTP_REFERER', -2)
maybe?

- 95
- 1
- 9
-
I don't think that's possible. Can you use javascript 'back()' method? As far as I know history is not accessible for security/privacy reasons. If those pages are within your own site you can store the history your self on a cookie or local storage – gtalarico Jul 20 '18 at 06:50
-
Django's `META['HTTP_REFERER']` is is nothing but HTTP's `Referer` header. It only contains the address of the previous page. – xyres Jul 20 '18 at 06:51
2 Answers
This won't be possible unless you implement some Session management to store the users referer history during their browsing session.
This could be implemented through a custom Middleware as so:
1.Get the current users session as the request comes in.
2.Add the current referer to a list in the session.
session = request.session
referer = request.META.get("HTTP_REFERER")
if "referers" in session:
session["referers"] = [referer]
else:
session["referers"] = [referer] + session["referers"]
3.In your views access the request.session["referers"]
attribute.
if request.session["referers"] and len(request.session["referers"]) > 1:
print(request.session["referers"][1])
else:
print("Less than 1 referer")
I won't be elaborating on implementing Django's session storage or a custom middleware as that is a lot more code, so you will need to understand how to use Django's middleware and session storage from the docs. In particular you need to decide how you want to store session (database is an easy solution if you already have one), and you may need to troubleshoot the order of your middleware because Django initialises the Session manager in its own middleware, so that must be executed before you access the session.
This may be more work than you intended, however you need to persist the previous referer somewhere and be able to track the users session.
Good luck.

- 7,731
- 2
- 31
- 46