Inserting the absolute URI of a page into a Django template

To add the absolute URI from a template, you can use Django's built in buildabsoluteuri method.

First, you need to add the request context preprocessor to your file.


Then, from a Django template, you can add the following tag to generate the full URI.

 {{ request.build_absolute_uri }}

If you are using this to generate a url for a social media link, you can also pipe in the urlencode function to encode the uri you are generating.

{{ request.build_absolute_uri|urlencode }}

example: Generate social media buttons that allow the user to share the current page on facebook, twitter, or google plus using request.build_absolute_uri and urlencode

<section class="share-buttons">
    <a class="share-facebook" href="{{ request.build_absolute_uri|urlencode }}"
        onclick=", 'facebook-share','width=580,height=296');return false;">
        <span class="hidden">Facebook</span>
    <a class="share-twitter" href="{{ article.title }}&url={{ request.build_absolute_uri|urlencode }}"
        onclick=", 'twitter-share', 'width=550,height=235');return false;">
        <span class="hidden">Twitter</span>
    <a class="share-google-plus" href="{{ request.build_absolute_uri|urlencode }}"
       onclick=", 'google-plus-share', 'width=490,height=530');return false;">
        <span class="hidden">Google+</span>

more Django posts