Tweet from Django application using Tweepy

Tweet from Django application using Tweepy

In this tutorial, we will learn how to post a tweet from Django application using Tweepy.

Sample Project

$ mkdir tweet-from-django && cd tweet-from-django
$ pipenv install django tweepy
$ pipenv shell
$ django-admin startproject config .
$ python startapp posts

Open and make the following changes:


Open the in posts application and make it look like the following:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return f"/posts/{}"

Run database migrations using the following commands.

$ python makemigrations
$ python migrate

Twitter API KEYS

Go to and get your keys.
Create a new application and click Complete.

Copy the API and API secret key and click on App settings, then click on Keys and Settings tab and scroll down to Authentication Tokens and generate Access Token & Secret keys and copy the Access Token and Access Secret key.
Make sure that Access Token & Secret have Read and Write permissions.

Inside posts application create file and add the following:

import tweepy as tweepy
from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import Post

@receiver(post_save, sender=Post)
def tweet_post(sender, instance, **kwargs):
    twitter_auth_keys = {
        "consumer_key": "API KEY HERE",
        "consumer_secret": "API SECRET KEY",
        "access_token": "ACCESS TOKEN HERE",
        "access_token_secret": "ACCESS TOKEN SECRET KEY HERE"

    auth = tweepy.OAuthHandler(
    api = tweepy.API(auth)

    tweet = instance.title + '\n' + Post.get_absolute_url(instance) 
    except tweepy.TweepError as error:
        if error.api_code == 187:
            print('duplicate message')

This is only for testing purpose, never put API credentials in code, put them in Environment variables.

Open and import the signals module like this:

from django.apps import AppConfig

class PostsConfig(AppConfig):
    name = 'posts'

    def ready(self):
        import posts.signals

Python interactive shell
We will use the interactive Python shell to create new post. To start the Python shell, use the following command:

$ python shell

>>> from posts.models import Post
>>> Post.objects.create(title='My First Post', content='My First Content')
If everything worked then you should check your twitter account with the new tweet from your application.

Check out sample project at GitHub

Share this: