3

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?

1

1 Answer 1

11

You can use urlparse module to extract the path:

try: from urllib.parse import urlparse # Python 3 except ImportError: from urlparse import urlparse # Python 2 parsed = urlparse('http://stackoverflow.com/questions/32809595') print(parsed.path) 

Output:

'/questions/32809595' 
Sign up to request clarification or add additional context in comments.

3 Comments

Note: in python 2, the relevant module is urlparse: docs.python.org/2/library/urlparse.html
Why was I looking in the Django modules? Of course Python already has one for that. Thank you very much. I need to sleep ;)
python3: import urllib urllib.parse.urlparse('urlhere')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.