DEV Community

Filip Němeček
Filip Němeček

Posted on

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

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

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('{0}'.format(post.get_absolute_url()))
    text = urllib.parse.quote_plus(post.title)
    tweet_intent = "{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:

"{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.

Top comments (0)