lbxa0q
Last Updated: December 08, 2016
·
19.1K
· tijs
Starbird crop2

Get the full url in any Django template

This tip outlines a simple way to get the full URL for the current page in your Django template. Without messing with the Sites framework which would get you another database hit.

Since this is something i need in almost every website i build (hello Facebook like button) i thought i'd write this one down for posterity.

What we are going to do is use the built-in buildabsoluteuri method of the request object. Watch this...

In settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
  # ...
  'django.core.context_processors.request',
  # ...
)

Which makes {{ request }} available in your templates. Then in your template you can do:

{{ request.build_absolute_uri }}

To get the full URI including the http:// and the domain. If your using this to pass the current URL to a Facebook like button you might want to encode that URL like so:

{{ request.build_absolute_uri|urlencode }}

And that's it! No messing with Sites or middleware nonsense needed.

Say Thanks
Respond

1 Response
Add your response

10255
E4b71bc8bd0e6bfe2809f357b2ebf4ba

As simple as it gets! Thank you!

over 1 year ago ·