4

I've been trying to find the previous url following this answer:

Django request to find previous referrer

So, in my .py I did:

print request.META
print request.META.HTTP_REFERER
print request.META['HTTP_REFERER']

request.META returns:

{'RUN_MAIN': 'true', 'HTTP_REFERER': 'http://127.0.0.1:8000/info/contact/', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/user', 'QT4_IM_MODULE': 'xim',....

So, I can see HTTP_REFERER is there, but when trying to access it either way I get the error:

<type 'exceptions.AttributeError'>
'dict' object has no attribute 'HTTP_REFERER'

How can I access it?

Community
  • 1
  • 1
Didina Deen
  • 195
  • 2
  • 17
  • Your second line is throwing this, right? –  Nov 16 '16 at 08:26
  • Your third line is correct. The second is not, thus the exception. And as the second raised an exception, the third is never executed. – spectras Nov 16 '16 at 08:26

3 Answers3

6

I would suggest:

request.META.get('HTTP_REFERER')
sheilapbi
  • 325
  • 1
  • 15
  • Note that this has a different behavior. It will return `None` if the header is not in `META`, instead of raising a `KeyError` exception. Depending on what you do with the value, it's a useful shorthand for catching the exceptin or it might let a miss go unnoticed. – spectras Nov 16 '16 at 08:43
4

request.META is a dictionary. Your code fails when you do

print request.META.HTTP_REFERER

Because you are trying to access HTTP_REFERER as attribute, but you should access it as item with

print request.META['HTTP_REFERER']

If you are not sure that you have this item in request.META you can use get method as other answerers suggested

print request.META.get('HTTP_REFERER', '')

This will output request.META['HTTP_REFERER'] if HTTP_REFERER is in request.META otherwise it will print '' which you provided as second argument to get. '' will be default value.

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
2

try: request.META.get("HTTP_REFERER", "")

orange
  • 31
  • 1