75

I'm passing the request to the template page.In django template how to pass the last page from which the new page was initialised.Instead of history.go(-1) i need to use this

 {{request.http referer}} ??

 <input type="button" value="Back" /> //onlcick how to call the referrer 
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Rajeev
  • 44,985
  • 76
  • 186
  • 285

4 Answers4

154

That piece of information is in the META attribute of the HttpRequest, and it's the HTTP_REFERER (sic) key, so I believe you should be able to access it in the template as:

{{ request.META.HTTP_REFERER }}

Works in the shell:

>>> from django.template import *
>>> t = Template("{{ request.META.HTTP_REFERER }}")
>>> from django.http import HttpRequest
>>> req = HttpRequest()
>>> req.META
{}
>>> req.META['HTTP_REFERER'] = 'google.com'
>>> c = Context({'request': req})
>>> t.render(c)
u'google.com'
Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
26

Rajeev, this is what I do:

 <a href="{{ request.META.HTTP_REFERER }}">Referring Page</a>
Jeff Bauer
  • 13,890
  • 9
  • 51
  • 73
  • friend, I want to implement it on the item selection page(which is a bootstrap modal). when the user wants to add a product to his wishlist, I want a link to the products page and a back button to the wishlist page ( which is a form in that BS modal). I used it, but it takes me back to the page that contains the modal, Can I go back to the page with that modal open and have the same values in the input boxes which is in it? – Shahriar.M Dec 24 '20 at 14:41
10

This worked for me request.META.get('HTTP_REFERER') With this you won't get an error if doesn't exist, you will get None instead

2

With 2 lines of code below, I could get referer in overridden get_queryset() in Django Admin:

# "store/admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
        
    def get_queryset(self, request):

        print(request.META.get('HTTP_REFERER')) # Here
        print(request.headers['Referer']) # Here
        
        return super().get_queryset(request)

Output on console:

http://localhost:8000/admin/store/person/ # request.headers['Referer']
http://localhost:8000/admin/store/person/ # request.META.get('HTTP_REFERER')
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129