Django January 19, 2026 4 min read

How to Integrate Twilio WhatsApp with Django: A Complete Guide

Learn how to integrate Twilio WhatsApp with your Django project in this comprehensive, step-by-step guide. Discover best practices for sending WhatsApp notifications, handling opt-in compliance, using message templates, and troubleshooting delivery issues. Perfect for developers seeking a secure, scalable, and professional WhatsApp messaging solution with Django and Python.

A
azzani
45 views
How to Integrate Twilio WhatsApp with Django: A Complete Guide

Table of Contents

  • Loading table of contents...

How to Integrate Twilio WhatsApp with Django: A Complete Guide

 

Introduction

WhatsApp is one of the world’s most popular messaging platforms, making it a powerful channel for business notifications, alerts, and customer engagement. Twilio, a leading cloud communications platform, provides a robust API for sending WhatsApp messages programmatically. Integrating Twilio WhatsApp with Django, a popular Python web framework, enables you to automate notifications, support chatbots, and enhance user experience in your web applications.

In this comprehensive guide, you’ll learn how to set up Twilio for WhatsApp, configure your Django project, and implement a professional, scalable WhatsApp notification system. This article covers best practices, security considerations, and troubleshooting tips to ensure a smooth integration.


Table of Contents

  1. Why Use WhatsApp with Django?
  2. Prerequisites
  3. Setting Up Twilio for WhatsApp
  4. Configuring Your Django Project
  5. Implementing WhatsApp Messaging in Django
  6. Handling Opt-In and Compliance
  7. Sending WhatsApp Notifications
  8. Receiving and Handling WhatsApp Messages
  9. Best Practices and Security
  10. Troubleshooting Common Issues
  11. Conclusion

Why Use WhatsApp with Django?

  • Global Reach: WhatsApp has over 2 billion users worldwide.
  • Instant Notifications: Deliver time-sensitive alerts, OTPs, and updates directly to users.
  • Rich Messaging: Support for text, images, documents, and interactive templates.
  • Automation: Integrate with Django’s backend logic for seamless workflows.

Prerequisites

  • A verified Twilio account.
  • A Django project (Django 3.x or 4.x recommended).
  • Python 3.7+.
  • Basic knowledge of Django models, views, and settings.
  • Access to your project’s codebase and environment variables.

Setting Up Twilio for WhatsApp

1. Register for Twilio and Enable WhatsApp

  • Sign up or log in to your Twilio account.
  • Navigate to the Twilio Console.
  • Go to Messaging > Senders > WhatsApp Senders.
  • Follow the steps to enable WhatsApp on a Twilio phone number. You may use the Sandbox for development or request production access for live messaging.

2. Configure WhatsApp Templates

  • WhatsApp requires all outbound business-initiated messages to use pre-approved templates.
  • In the Twilio Console, go to Messaging > Content Template Builder.
  • Create and submit your message templates for approval (e.g., OTP, notification, alert).
  • Once approved, note the Template SID for each template.

3. Gather Your Twilio Credentials

  • Account SID and Auth Token: Found in your Twilio Console dashboard.
  • WhatsApp-enabled Phone Number: The number you’ll use to send messages.
  • Template SIDs: For each approved WhatsApp template.

Important: Never hard-code sensitive credentials in your codebase. Use environment variables or Django’s settings module.


Configuring Your Django Project

1. Install Required Packages

pip install twilio django-environ

 

2. Update Django Settings

Add your Twilio credentials and WhatsApp configuration to your settings.py or .env file 

# settings.py
import environ

env = environ.Env()
environ.Env.read_env()

TWILIO_ACCOUNT_SID = env('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = env('TWILIO_AUTH_TOKEN')
TWILIO_WHATSAPP_FROM = env('TWILIO_WHATSAPP_FROM')  # e.g., 'whatsapp:+1234567890'
TWILIO_TEMPLATE_SID_OTP = env('TWILIO_TEMPLATE_SID_OTP')
# Add other template SIDs as needed

 

.env file example:

TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_WHATSAPP_FROM=whatsapp:+1234567890
TWILIO_TEMPLATE_SID_OTP=HXxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 

Implementing WhatsApp Messaging in Django

1. Create a Twilio WhatsApp Service

Create a reusable service class for sending WhatsApp messages:

# services/twilio_whatsapp_service.py
from twilio.rest import Client
from django.conf import settings

class TwilioWhatsAppService:
    def __init__(self):
        self.client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
        self.from_number = settings.TWILIO_WHATSAPP_FROM

    def send_template_message(self, to_number, template_sid, variables):
        message = self.client.messages.create(
            from_=self.from_number,
            to=f'whatsapp:{to_number}' if not to_number.startswith('whatsapp:') else to_number,
            content_sid=template_sid,
            content_variables=variables
        )
        return message.sid, message.status

 

2. Integrate with Django Views or Tasks

You can call this service from your Django views, forms, or background tasks (e.g., Celery) to send WhatsApp notifications.


Handling Opt-In and Compliance

WhatsApp requires explicit user opt-in for ongoing notifications. For OTPs or one-time codes, user action (such as entering their number and requesting a code) is considered opt-in.

  • Store opt-in status in your user model.
  • Respect opt-out requests and provide a way for users to unsubscribe.

Example user model fields:

class User(models.Model):
    # ... existing fields ...
    whatsapp_number = models.CharField(max_length=20, blank=True, null=True)
    whatsapp_opt_in = models.BooleanField(default=False)
    whatsapp_opt_in_date = models.DateTimeField(null=True, blank=True)

 

Sending WhatsApp Notifications

1. Prepare Template Variables

Each template requires specific variables. Prepare them as a dictionary:

variables = {
    '1': user.first_name,
    '2': 'Your OTP code is 123456'
}

 

2. Send the Message

service = TwilioWhatsAppService()
sid, status = service.send_template_message(
    to_number=user.whatsapp_number,
    template_sid=settings.TWILIO_TEMPLATE_SID_OTP,
    variables=variables
)

 

3. Handle Delivery Status

Monitor delivery status via Twilio’s Message Logs or by setting a status callback URL.


Receiving and Handling WhatsApp Messages

To receive inbound WhatsApp messages (e.g., for chatbots or opt-in confirmation):

  • Set up a webhook endpoint in Django.
  • Configure your Twilio WhatsApp sender to POST incoming messages to your endpoint.

Example Django view:

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def whatsapp_webhook(request):
    if request.method == 'POST':
        from_number = request.POST.get('From')
        body = request.POST.get('Body')
        # Process the message as needed
        return HttpResponse('OK')
    return HttpResponse(status=405)

 

Best Practices and Security

  • Never expose your Twilio credentials in public repositories.
  • Use environment variables for all sensitive data.
  • Validate phone numbers before sending messages.
  • Log all message sends and errors for auditing and troubleshooting.
  • Use approved templates for all outbound business-initiated messages.
  • Respect user privacy and opt-out requests.

Troubleshooting Common Issues

  • Messages not delivered?

    • Check Twilio Message Logs for error codes.
    • Ensure the recipient’s number is WhatsApp-enabled and correct.
    • Verify that you are using an approved template and all variables are provided.
  • Template not sending?

    • Confirm the template is approved and the SID is correct.
    • Check that all required variables are present and match the template format.
  • User not receiving messages after 24 hours?

    • Only template messages can be sent outside the 24-hour window.
    • Free-form messages are only allowed within 24 hours of the user’s last message.
  • Rate limits or account issues?

    • Check your Twilio Console for any warnings or restrictions.

____________________________________

By Azzani

Related Articles

Discussion 0

No comments yet. Be the first to start the discussion!

Leave a Comment