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 manage.py startapp posts

Open settings.py and make the following changes:


INSTALLED_APPS = [
    ...
    'posts.apps.PostsConfig',
    ...
]

Open the models.py 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/{self.id}"


Run database migrations using the following commands.


$ python manage.py makemigrations
$ python manage.py migrate

Twitter API KEYS

Go to https://dev.twitter.com/apps 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 signals.py 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(
        twitter_auth_keys['consumer_key'],
        twitter_auth_keys['consumer_secret']
    )
    auth.set_access_token(
        twitter_auth_keys['access_token'],
        twitter_auth_keys['access_token_secret']
    )
    api = tweepy.API(auth)

    tweet = instance.title + '\n' + Post.get_absolute_url(instance) 
    
    try:
        api.update_status(tweet)
    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 apps.py 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 manage.py 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: