Is there a way to create a back button in Django that understands a tree structure?

I have a Django website that looks like this:

enter image description here

The arrows represent hyperlinks that take you to the next page. All pages except the Main Page need a “Back” button.

For Page A and Page B, the back button is pretty simple – it always takes you to the Main Page.

For Page C however, there are 2 different ways to get to it (technically 3, if you count the back button on Page D), so it’s no longer obvious where the back button should take you.

The way it should work is this:

  • If the user came from Page A to get to Page C, the Back button should take them back to Page A
  • If the use came from Page B to get to Page C, the Back button should take them back to Page B
  • If the user didn’t come from either Page A or Page B to get to Page C (they could have just entered the URL of Page C into their browser), default to having the Back button take them to Page A

This has been asked before, and none of the answers/suggestions make sense for anything other than the most basic scenario, where Page C is the end node.

The problem:

  • Using a hardcoded url for the back button of Page C won’t work, because there are 2 ways to get to it
  • Using session to keep a single variable that keeps track of whether you last visited Page A or Page B won’t work because multiple browser tabs share the same session variables. If the user has 2 tabs of our website open, navigating around will lead to confusion as both will update the same session variable
  • Using request.META.HTTP_REFERER won’t work, because the user might navigate to Page D, and then back to Page C, so the HTTP_REFERER variable will point to Page D, rather than Page A or Page B
  • Using javascript:history.go(-1) won’t work – same problem as above with HTTP_REFERER

I have come across this issue in multiple projects, and it’s always a pain to deal with. The solution is always hacky. Is this a problem that inherently can’t be handled by Django, and must be handled by something like JavaScript’s sessionStorage?