tags:

views:

49

answers:

1

I want to be able to create a back link to the referring URL, if the referrer was a view, and if it was not a view, a back link to a default page (Don't ask... it's kind of a weird requirement).

Basically, if the user came to the page in question from another view on the same django site, the back link should be a return to that view.

If the user came in from an external site, the back link should go to a default view.

Javascript is not an ideal solution, although I'm willing to consider it if there's no other way.

+2  A: 

Use django.core.urlresolvers.resolve to figure out if it's an internal Django URL or not. If it is not, it will raise django.core.urlresolvers.Resolver404, otherwise it will return a match object you can introspect if necessary. You can feed the REFERER environment variable to this as necessary, and replace the URL with a default URL if resolve raises Resolver404.

edit: Actually, no, resolve apparently only works with path components of URLs. So you'd have to deconstruct the REFERER header using urlparse to figure out if it's the right domain, and if it is, use resolve on the path component of the parsed URL to figure out if the URL is part of your Django site or not.

# code not tested, YMMV, etc. 

from urlparse import urlparse

from django.core import urlresolvers

HOME = 'http://my.site.com/'

def generate_back_url(url, default_url=HOME):
    parsed = urlparse(url)
    if parsed.netloc == 'my.site.com':
        try:
            urlresolvers.resolve(parsed.path)
        except urlresolvers.Resolver404:
            back_url = default_url
        else:
            back_url = url
    else:
        back_url = default_url
    return back_url

# ...

def my_view(request):
    # ...
    # truth be told I'm not sure whether the .get() is necessary, sorry.
    back_url = generate_back_url(request.META.get('REFERER', HOME))
    # ...
Devin Jeanpierre