django

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 settings.py file.

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.request",
)

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="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri|urlencode }}"
        onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;">
        <span class="hidden">Facebook</span>
    </a>
    <a class="share-twitter" href="http://twitter.com/share?text={{ article.title }}&url={{ request.build_absolute_uri|urlencode }}"
        onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;">
        <span class="hidden">Twitter</span>
    </a>
    <a class="share-google-plus" href="https://plus.google.com/share?url={{ request.build_absolute_uri|urlencode }}"
       onclick="window.open(this.href, 'google-plus-share', 'width=490,height=530');return false;">
        <span class="hidden">Google+</span>
    </a>
</section>

more Django posts