Adding SMS messaging to your Django application with Twilio
Step 1
$ pip install django-twilio
Step 2
INSTALLED_APPS = (
'django_twilio',
...
)
Step 3
$ python manage.py syncdb
Step 4
$ python manage.py migrate django_twilio
Step 5
TWILIO_ACCOUNT_SID = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
TWILIO_AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY'
Step 6
from twilio.rest import TwilioRestClient
from django.conf import settings
def awesome_method(request):
message = 'Hi David'
from_ = '+15556667777'
to = '+15556667771';
client = TwilioRestClient(
settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
response = client.messages.create(
body=message, to=to, from_=from_)
#do something with response
Step 7
from django.conf import settings
from twilio.rest import TwilioRestClient
from django.template.loader import render_to_string
def send_sms(to, message, content={}, template=None):
'''sms utility method'''
content.update({
'put any content here'
})
if not template:
'''If we have a template format the message'''
message = render_to_string(template, content)
message = message.encode('utf-8')
client = TwilioRestClient(
settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
response = client.messages.create(
body=message, to=to, from_='+15556667777')
return response
Step 8
{% if back_up %}
Hi {{name}, the website {{site_name}} [{{site_link}}] is back up at {{when}}.
{% else %}
Hi {{name}, the website {{site_name}} [{{site_link}}] is down at {{when}}.
{% endif %}
Step 9
from app.utils import send_sms
def downtime_monitor():
content = {'when':timezone.now(),'name':user.name,'back_up':back_up}
message = ''
template = 'downtime_alert.html'
to = user.phonenumber
response = send_sms(to, message, content, template)
#do something with response