MQTT is a lightweight IoT messaging protocol based on a publish/subscribe model, providing real-time, reliable messaging services for connected devices with minimal code and bandwidth. Due to its efficiency, MQTT is widely used in IoT, mobile applications, smart hardware, Internet of vehicles, and energy sectors.
Django is a popular open-source Python web framework known for its scalability and rapid development capabilities. This guide will walk you through integrating MQTT with Django, covering how to connect, subscribe, unsubscribe, and exchange messages between an MQTT client and an MQTT broker within a Django project.
We will use the paho-mqtt library, a widely used MQTT client library in Python that supports MQTT 5.0, 3.1.1, and 3.1 on Python 2.7 and 3.x.
This project is tested on Python 3.12. You can verify your Python version with:
$ python3 --version
Python 3.12.2
Install Django and paho-mqtt
using Pip.
pip3 install django
pip3 install paho-mqtt
Create a Django project.
django-admin startproject django_mqtt
The directory structure after creation is as follows.
├── django_mqtt
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
This article will use free public MQTT Broker provided by EMQ. The service is created based on EMQX Platform. The server access information is as follows:
- Broker:
broker.emqx.io
- TCP Port:
1883
- Websocket Port:
8083
import paho.mqtt.client as mqtt
Handling successful or failed MQTT connections in the callback function. After a successful connection, we subscribe to the django/mqtt
topic:
def on_connect(mqtt_client, userdata, flags, rc):
if rc == 0:
print('Connected successfully')
mqtt_client.subscribe('django/mqtt')
else:
print('Bad connection. Code:', rc)
This function will print the messages received by the django/mqtt
topic.
def on_message(mqtt_client, userdata, msg):
print(f'Received message on topic: {msg.topic} with payload: {msg.payload}')
Add configuration items for the MQTT broker in settings.py
. For any questions about the following configuration items and MQTT-related concepts mentioned in this article, please check out the blog: The Easiest Guide to Getting Started with MQTT.
This example uses anonymous authentication, so the username and password are set to empty.
MQTT_SERVER = 'broker.emqx.io'
MQTT_PORT = 1883
MQTT_KEEPALIVE = 60
MQTT_USER = ''
MQTT_PASSWORD = ''
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD)
client.connect(
host=settings.MQTT_SERVER,
port=settings.MQTT_PORT,
keepalive=settings.MQTT_KEEPALIVE
)
We create a simple POST API to implement MQTT message publishing.
In actual applications, the API code may require more complex business logic processing.
Add the following code in views.py
.
import json
from django.http import JsonResponse
from django_mqtt.mqtt import client as mqtt_client
def publish_message(request):
request_data = json.loads(request.body)
rc, mid = mqtt_client.publish(request_data['topic'], request_data['msg'])
return JsonResponse({'code': rc})
Add the following code in urls.py
.
from django.urls import path
from . import views
urlpatterns = [
path('publish', views.publish_message, name='publish'),
]
Add the following code in __init__.py
.
from . import mqtt
mqtt.client.loop_start()
At this point, we have finished writing all the code, and the full code can be found at GitHub.
Finally, execute the following command to run the Django project.
python3 manage.py runserver
When the Django application starts, the MQTT client will connect to the MQTT Broker and subscribe to the topic django/mqtt
.
Next, we will use MQTT client - MQTTX to test connection, subscription, and publishing.
-
Create an MQTT connection in MQTTX, enter the connection name, leave the other parameters as default, and click the
Connect
button in the upper right corner to connect to the broker. -
Publish the message
Hello from MQTTX
to thedjango/mqtt
topic in the message publishing box at the bottom of MQTTX. -
The messages sent by MQTTX will be visible in the Django runtime window.
$ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). Django version 5.1.5, using settings 'django_mqtt.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Connected successfully Received message on topic: django/mqtt with payload: b'Hello from MQTTX'
-
Subscribe to the
django/mqtt
topic in MQTTX. -
Use Postman to call
/publish
API: publish the messageHello from Django
to thedjango/mqtt
topic. -
You will see the messages sent by Django in MQTTX.
In this guide, we integrated MQTT with Django using the paho-mqtt library, enabling message publishing and subscription via an MQTT broker. This foundation can be extended to support more advanced use cases, such as real-time IoT applications, device monitoring, or remote control systems.
For further learning, explore our Easy-to-understand Guide to MQTT Protocol to dive deeper into MQTT’s advanced features and real-world applications.