Django and Twilio Quickstart Guide

June 24, 2020, 12:33 p.m.

Django · 4 min read

Django and Twilio Quickstart Guide

What is Twilio?

Twilio is known as a cloud communications platform as a service company (CPaaS) since they provide developers with the ability to programmatically make and receive calls as well as send and receive text messages.  Using their API, developers can automate and schedule text messages to remind users of upcoming appointments, run sweepstakes, and create chatbots.  However, use cases are not limited to these options.  A quick look at Twilio's Solutions page reveals how developers can use Twilio for two-step authentication, SMS surveys, and anonymous communications.  

 

Why Twilio and Django?

Imagine a client needs to send a mass text campaign to all of their customers.  The client wants to be able to upload a file of their customer's phone numbers in an admin panel and then send a new offer with a promo code via a mass text.  Fortunately, Django and Twilio can easily integrate to form this solution.  Twilio's docs go over their Python helper library here.  For our project, we will consult this page and create a Customer model to store a name and phone number.   Then we will extend Django's admin to send out text messages by creating messages with the official helper library.  Keep in mind, this integration is relatively straightforward but can be further customized to create chatbots and call routing systems.  

 

Django Setup

First set up your virtual environment.  Note: For macOS/ubuntu users replace py with python3 

C:\Users\Owner\Desktop\code>py -m venv text

 

Next activate the virtual environment, install Django using a package manager, create a project (mysite), and lastly create an app (main).

C:\Users\Owner\Desktop\code>cd text

C:\Users\Owner\Desktop\code\text>Scripts\activate

(text) C:\Users\Owner\Desktop\code\text>pip install Django

(text) C:\Users\Owner\Desktop\code\text>django-admin startproject mysite

(text) C:\Users\Owner\Desktop\code\text>cd mysite

(text) C:\Users\Owner\Desktop\code\text\mysite>py manage.py startapp main

 

Add the main app to INSTALLED_APPS in settings.py.

mysite/settings.py

INSTALLED_APPS = [
    'main.apps.MainConfig', #add this
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

 

Create a superuser:

py manage.py createsuperuser

 

Next, we are going to create a model in models.py to store the name and phone number for a customer.  But first, to store phone numbers let's install the django-phonenumber-field package. 

pip install django-phonenumber-field[phonenumbers]

 

Add to INSTALLED_APPS:

mysite/settings.py:

INSTALLED_APPS = [
    ...
    'phonenumber_field',
    
]

 

Then create the model, makemigrations, and migrate.

models.py

from django.db import models
from phonenumber_field.modelfields import PhoneNumberField


class Customer(models.Model):
	name = models.CharField(max_length=200)
	phone_number = PhoneNumberField()

py manage.py makemigrations
py manage.py migrate

 

Also, add the model to the Django admin:

main/admin.py

from django.contrib import admin
from .models import Customer

admin.site.register(Customer)

 

Now let's add a customer via the admin panel.  Unlike the example below, enter a valid phone number so you can verify the message we will send.  

name: James

phone number: +12222222222

 

Twilio Integration

After creating a customer let's set up our project to use Twilio's REST API by installing the official Python helper library.

pip install twilio

 

Visit twilio.com to get started with a trial account.  No credit card is necessary.  After signing up, choose a trial phone number from the dashboard.  Next, locate both your ACCOUNT SID and AUTH TOKEN.  

Twilio Dashboard

 

Add ACCOUNT SID and AUTH TOKEN to your project's settings.  Note: These variables should be kept safe in production using a solution such as python-decouple

mysite/settings.py

TWILIO_ACCOUNT_SID = 'YOUR_ID_HERE'
TWILIO_AUTH_TOKEN = 'YOUR_TOKEN_HERE'

 

Instead of creating a view to handle the text message, we are going to simplify things even further by adding a function to admin.py.  In the Django admin panel, we will be able to select which customers we want and then choose "Send text campaign" from the dropdown menu.  To actually send a text message, we instantiate a client object with our account ID and authorization token.  Then, for each customer selected in the admin, we create a message by specifying the "to" phone number, using our trial number as the "from" number, and finally inserting our message as the body.  

main/admin.py:

from django.contrib import admin
from .models import Customer
from twilio.rest import Client
from django.conf import settings


def send_text(modeladmin, request, queryset):
	client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN )
	for customer in queryset:
		message = client.messages.create(
			to= str(customer.phone_number), 
			from_="+13156403238", # insert trial number 
			body="Hey I hope you received this message") # insert message
send_text.short_description = "Send text campaign"

class CustomerAdmin(admin.ModelAdmin):
	fields = ('name', 'phone_number' )

	actions = [send_text]



admin.site.register(Customer, CustomerAdmin)

admin twilio

 

Final Thoughts

You should receive a text message when sending a campaign from the admin panel and that's it!  You can now send text messages with Twilio.  Feel free to upgrade from the trial version if you are looking to use this solution in production.  Of course, there's still a lot that can be added.  For example, your application can send text messages, but how about receiving them?  We recommend checking out django-twilio since the package comes with URLs and decorators to easily route incoming messages to the appropriate view.  Let us know if you are curious about what else you can build with Twilio.


0
Subscribe now

Subscribe to stay current on our latest articles and promos





Post a Comment
Join the community

0 Comments