1) Create a Django project
C:\Users\Owner\Desktop\code>py -m venv text
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
2) Configure Django settings.py
INSTALLED_APPS = [
'main.apps.MainConfig', #add this
...
]
3) Create a superuser
py manage.py createsuperuser
4) Install the django-phonenumber-field package
pip install django-phonenumber-field[phonenumbers]
5) Add django-phonenumber-field to the settings.py
INSTALLED_APPS = [
...
'phonenumber_field', #add this
...
]
6) Create the model in 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()
7) Make migrations and migrate
py manage.py makemigrations
py manage.py migrate
8) Add the model to the admin.py
from django.contrib import admin
from .models import Customer
admin.site.register(Customer)
9) Add a customer via the Django admin panel
10) Install the official Twilio Python helper library
pip install twilio
11) Visit twilio.com, create a trial account, choose a trail phone number, and locate your ACCOUNT SID and AUTH TOKEN
12) Add your ACCOUNT SID and AUTH TOKEN to the Django settings.py.
These variables should be kept safe in production using a solution such as python-decouple.
TWILIO_ACCOUNT_SID = 'YOUR_ID_HERE'
TWILIO_AUTH_TOKEN = 'YOUR_TOKEN_HERE'
13) Handle text message setup in the 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)
14) Log back into the Django admin panel, select the customers model, select the customers, change the action to "Send text campaign" and click "Go" to send the text.
Top comments (0)