In a Django 1.8 simple tag, I need to resolve the path to the HTTP_REFERER found in the context. I have a piece of code that works, but I would like to know if a more elegant solution could be implemented using Django tools.
Here is my code :
from django.core.urlresolvers import resolve, Resolver404 # [...] @register.simple_tag(takes_context=True) def simple_tag_example(context): # The referer is a full path: http://host:port/path/to/referer/ # We only want the path: /path/to/referer/ referer = context.request.META.get('HTTP_REFERER') if referer is None: return '' # Build the string http://host:port/ prefix = '%s://%s' % (context.request.scheme, context.request.get_host()) path = referer.replace(prefix, '') resolvermatch = resolve(path) # Do something very interesting with this resolvermatch... So I manually construct the string 'http://sub.domain.tld:port', then I remove it from the full path to HTTP_REFERER found in context.request.META. It works but it seems a bit overwhelming for me.
I tried to build a HttpRequest from referer without success. Is there a class or type that I can use to easily extract the path from an URL?