Justin Duke

Getting the current absolute URL as a Django variable

A quick snippet that may save you some time, as it did this evening:

For blog posts like this and recipes like this, I wanted to add a nice little sharing snippet for Twitter and Facebook for the rote and boring social media/marketing reasons. (It’s on the bottom of this page.)

I’m not a huge fan of using the standard share buttons that Facebook and Twitter provide: they involve frontloading either an iframe or an external script and break up the aesthetics of the page.

So the answer was just to create a basic link – but you need to seed it with a URL to actually create the link. This is trivial to do with javascript, but I didn’t want to rely on something client-side since it seems like Django should be able to provide this in the template context.

Turns out they do, and its out of the box! All you have to do is hit up {{ request.build_absolute_uri }}.

So something like this:

<a href="https://getpocket.com/save?url={{request.build_absolute_uri}}">save it on pocket</a>

Resolves to this:

<a href="https://getpocket.com/save?url=https://getbarback.com/recipes/manhattan">save it on pocket</a>

Hope this saves you some time!

Liked this post? You should subscribe to my newsletter and follow me on Twitter.

(I've got an RSS feed, too, if you'd prefer.)