Django: Add tweet button with plain HTML/CSS, no JavaScript

nemecek_f profile image Filip Němeček ・2 min read

Do you want to have "Tweet" button on your personal site without the need to use Twitter JavaScript library? You can, and it only takes a bit of code. Twitter supports special "intent" url which can be configured to pre-populate new tweet on Twitter.com.

In this post I will show you how I integrated this into my site to give the readers option to quickly tweet my posts if they choose. I am so far not using any JavaScript because I don't need it and I didn't want to change this just for Twitter.

Let's get started.

The first step is to prepare the url in Django and send it to template where it can be rendered inside a tag.
I have created this handy helper method:

def get_tweet_intent(post: BlogPost):
    url = urllib.parse.quote('https://nemecek.be{0}'.format(post.get_absolute_url()))
    text = urllib.parse.quote_plus(post.title)
    tweet_intent = "https://twitter.com/intent/tweet?text={0}&url={1}&via=nemecek_f&hashtags={2}".format(text, url,
    return tweet_intent

It expects instance of BlogPost which is my model class for posts and returns tweet_intent as a string.

I am using the urlib.parse.quote method to correctly encode the url and also the quote_plus variant to encode title. The difference is that the "plus" version also encodes spaces.

Then it is just a matter of constructing the url.

The format is this:

"https://twitter.com/intent/tweet?text={tweet text}&url={url to link to}&via={ username or user id}&hashtags={ hashtags separated by comas}"

You can also check out the official docs.

Once you send it to the template as tweet_intent or anything else you want, you can create the element:

<a class="tweet-button" href="{{ tweet_intent }}" target="_blank">Tweet</a>

And possibly some styles 🙂

.tweet-button {
    float: right;
    padding: 5px 20px;
    background-color: #1DA1F2;
    color: white;
    border-radius: 5px;

The background color is the "Twitter blue".

And that is how you can create Tweet button with Django, HTML and CSS.

Posted on Feb 13 by:

nemecek_f profile

Filip Němeček


Primarily iOS developer, I also like Django and Python. And dabble with JavaScript occasionally. Love reading and coffee.


markdown guide