1
votes

Let's say we have a simple Django app with a blog model.

There are only 3 pages:

  1. Home page
  2. Blog index
  3. Blog post detail

The blog posts are listed in 3 locations:

  1. In a slider on the home page
  2. In the blog index (of course)
  3. At the bottom of a blog post

There are 2 main ways of using breadcrumbs I've seen on a site:

  1. Home / Blog / Blog Post
  2. < Back

I want to be able to have the "< Back" button go back to whichever the original source came from.

I'm aware this could be done with JavaScript.

But with Django, I've heard people say on another post that "you shouldn't redirect in a template, you should do it in view", but to me that makes no sense as how is the view supposed to know which page to go back to automatically?

Anyways, I'm trying to see is:

How would you link back to the source page you arrived at a blog post from (i.e., another post, the home page, or the blog index) using Django views or in the Django template?

1

1 Answers

1
votes

We can use the request object inside a Django view to find the referring link.

Here is the code for this:

request.META['HTTP_REFERER']

You could add the below code to your template context to add the link to your template context

{'previous_page': request.META['HTTP_REFERER']}

Then, we could use a link wrapping a button to redirect the user to the previous page when they press it.

<a href = "{{previous_page}}"><button type="button">Back</button></a>

More info about the request.META dictionary here:

https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META

Hope this helps