Miguel Ike
Miguel Ike

Reputation: 484

How to compare Referer URL in Django Request to another URL using reverse()?

How can I compare the referer URL and reverse() url?

Here is my current code:

if request.META.get('HTTP_REFERER') == reverse('dashboard'):
    print 'Yeah!'

But this doesn't work because the reverse will output /dashboard while HTTP_REFERER output http://localhost:8000/dashboard/

My current solution is:

if reverse('dashboard') in request.META.get('HTTP_REFERER'):
    print 'Yeah!'

I don't know if this is the best way to do this. Any suggestion would be great.

Upvotes: 3

Views: 2618

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

You can use urlparse to get the path element from a URL. In Python3:

from urllib import parse
path = parse.urlparse('http://localhost:8000/dashboard/').path

and in Python 2:

import urlparse
path = urlparse.urlparse('http://localhost:8000/dashboard/').path

Upvotes: 4

Related Questions