I'm using Django for a web site and needed to build a context processor to provide referrer (variable named referer
) information.
I have a simple if, elif, elif, else statement:
[ . . . ]
host = get_current_site(request)
local_url = SITE_URLS['local']
dev_url = SITE_URLS['dev']
prod_url = SITE_URLS['prod']
# print referer for debugging purposes - remove when done...
print("current host: {0}".format(host))
print("current urls: {0} {1} {2}".format(local_url, dev_url, prod_url))
# determine default referer - eg, set as host/site name
if host == prod_url:
referer = prod_url
elif host == dev_url:
referer = dev_url
elif host == local_url:
referer = local_url
else:
# set referer for current request
try:
referer = request.META['HTTP_REFERER']
except KeyError as e:
print('ERROR: key error - referer doesn\'t exist: {0}'.format(str(e)));
[ . . . ]
What's weird is that the print statements above yield the host
being equal to the local_url
(from console):
current host: http://localhost:8000
current urls: http://localhost:8000 [ . . . ]
Yet it is still evaluating the else > try and throwing a key error... The point is that only when the default host/site is not available, then the request.META['HTTP_REFERER']
is valid.
What is going wrong here? I'm missing something. Python is telling me that host != local_url
but why?
EDIT
Thanks to a great hint from @Martijn Pieters. I changed the print statements and now see this:
current host: <Site: http://localhost:8000>
current urls: 'http://localhost:8000'
I think I forgot to use the attributes for the sites framework:
Most likely you have a whitespace issue; replace your formatting with:
print("current host: {0!r}".format(host))
print("current urls: {0!r} {1!r} {2!r}".format(local_url, dev_url, prod_url))
to use repr()
values instead; these will include more information on the type of the value and any trailing whitespace will be immediately obvious.
If you see a django.contrib.sites.models.Site
object, compare against the domain
attribute:
if host.domain == prod_url: