Anupam
Anupam

Reputation: 15620

Getting 'path' of previous URL from template

I know I can get the previous URL in the template by using the following:

{{ request.META.HTTP_REFERER}}

But I want to know if I there's a way to get only the path and not the absolute URL (i.e /my-page instead of http://localhost:8000/my-page)

Like in the view we can do:

from urllib import parse
parse.urlparse(request.META.get('HTTP_REFERER')).path

Can I do something like that in the template as well?

Update (with more info): My usecase is to compare the previous url with another url within the same site to see if the user came in from there

Upvotes: 5

Views: 2041

Answers (2)

Anupam
Anupam

Reputation: 15620

Looks like there isn't a direct way to do that in the template, so this is what I ended up doing in the template to check if a particular (relative) url is part of the previous (absolute) URL :

{% url 'schoollist:add_school' as add_school_url %}
{% if add_school_url in request.META.HTTP_REFERER %} 
    Thanks for adding!
{% endif %}

Upvotes: 3

Frederik.L
Frederik.L

Reputation: 5620

A possible way to achieve this is to use urlparse to get components out of the referer URL, then get the relative path.

If you handle it with custom code this probably won't do much difference for basic cases but probably do some good with fancier edge cases:

from urlparse import urlparse
referer = request.META.get('HTTP_REFERER')
path = urlparse(referer).path

See: Parse URLs into components

Upvotes: 0

Related Questions