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))
# ...