Back to Blog
Integration Guides

How to Send SMS with Twilio and Django: Step-by-Step Tutorial

Integrate Twilio SMS into your Django application using the Twilio Python library with settings-based credentials and webhook views.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
7 min read
Twilio
Integration
SDK
Mobile
How to Send SMS with Twilio and Django: Step-by-Step Tutorial

Twilio SMS and Django integrate through the Twilio Python helper library installed with pip install twilio, with credentials stored in Django settings loaded from environment variables via python-decouple or django-environ, allowing you to dispatch SMS from Django views, signals, management commands, or Celery tasks throughout your project. This integration is used by Django development teams building web platforms, SaaS products, or internal tools that need SMS for OTP verification, system alerts, booking confirmations, or user notifications, and who want a well-tested Python library that fits Django's settings-based configuration pattern and integrates cleanly with Celery for async SMS dispatch. The Twilio client is instantiated with credentials from settings.py, SMS is dispatched from a service module that wraps the client, and inbound Twilio webhooks are handled by a Django view that outputs TwiML XML using the twilio Python library's TwiML builders.

What You Need Before You Start

Install the Twilio Python library by running pip install twilio and add it to your requirements.txt. Install python-decouple for environment variable management by running pip install python-decouple. Create a .env file at your Django project root with TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_FROM_NUMBER values from your Twilio Console. In settings.py, import config from decouple and add TWILIO_ACCOUNT_SID = config('TWILIO_ACCOUNT_SID'), TWILIO_AUTH_TOKEN = config('TWILIO_AUTH_TOKEN'), and TWILIO_FROM_NUMBER = config('TWILIO_FROM_NUMBER') so credentials are available as Django settings throughout the project. Add .env to .gitignore and provision a Twilio SMS-capable phone number in the Twilio Console.

Step-by-Step Integration Guide

Create a file at yourapp/services/twilio_service.py that imports Client from twilio.rest and imports settings from django.conf, then defines a send_sms(to, body) function that instantiates client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN), calls message = client.messages.create(to=to, from_=settings.TWILIO_FROM_NUMBER, body=body), and returns message.sid. Wrap the create call in try/except catching twilio.base.exceptions.TwilioRestException, log with Python's logging module, and re-raise or return None to let the caller decide how to handle the failure. In a Django view that needs to send an SMS, import send_sms from yourapp.services.twilio_service and call it after form validation or business logic execution. For inbound SMS webhooks, create a Django view that imports MessagingResponse from twilio.twiml.messaging_response, constructs resp = MessagingResponse(), calls resp.message('Reply body') to add a response, and returns HttpResponse(str(resp), content_type='text/xml'). Add the inbound webhook URL to urls.py with path('sms/webhook/', views.sms_webhook, name='sms_webhook') and set it as the Messaging webhook URL in the Twilio Console for your phone number.

Common Issues and How to Fix Them

The Twilio client raises twilio.base.exceptions.TwilioRestException with HTTP status 401 when settings.TWILIO_ACCOUNT_SID or settings.TWILIO_AUTH_TOKEN is an empty string because decouple.config returned an empty string rather than raising an error when the variable exists in .env but has no value. Add decouple.config with cast=str and a default of None for each credential setting, then add a Django system check or AppConfig.ready() assertion that raises ImproperlyConfigured if any credential setting is None or empty. Django's CSRF middleware returns HTTP 403 for Twilio's incoming webhook POST because Twilio does not send a Django CSRF token cookie. Decorate the inbound webhook view with @csrf_exempt and add Twilio webhook signature validation using twilio.request_validator.RequestValidator with settings.TWILIO_AUTH_TOKEN, validating the X-Twilio-Signature header against the full request URL and POST parameters to reject spoofed requests. Celery tasks that call send_sms fail when the task runs in a worker that does not have the same environment variables as the Django process because the worker was started without loading the .env file. Ensure all Celery worker startup commands source the same environment variables or load the .env file using python-decouple's AutoConfig class in the Django settings file.

How to Get More from This Integration

Integrate Celery for async SMS dispatch by creating a Celery task decorated with @shared_task that calls send_sms and handles retries with self.retry(exc=exc, countdown=60, max_retries=3) inside the except block, then calling send_sms_task.delay(to, body) from Django views so the HTTP response returns immediately while the Twilio API call runs in a background worker. Build a Django management command for bulk SMS sending by creating management/commands/send_bulk_sms.py that reads a CSV file of phone numbers and messages passed as a command argument, iterates the rows, calls send_sms with rate limiting using time.sleep to respect Twilio's message rate limit of one message per second per long code, and logs each result, enabling bulk notifications to be triggered from the command line or a cron job. Add Twilio Verify to Django authentication by creating a verify-send view that calls Client.verify.v2.services(settings.TWILIO_VERIFY_SID).verifications.create(to=phone, channel='sms') and a verify-check view that calls verificationChecks.create(to=phone, code=submitted_code), setting the user session to verified on an approved status.

Conclusion

Django and Twilio together provide a well-structured SMS integration using Python's settings-based configuration and service layer patterns to keep dispatch logic reusable and testable. Contact Telphi Consulting to implement and configure Twilio SMS in your Django project.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.