EMQ Sponsors Open Source Summit Europe 2024 | Register Now →

How to Use MQTT in The Django Project

Oct 25, 2022
How to Use MQTT in The Django Project

MQTT is a lightweight IoT messaging protocol based on publish/subscribe model, which can provide real-time reliable messaging services for connected devices with very little code and bandwidth. It is widely used in industries such as IoT, mobile Internet, smart hardware, Internet of vehicles, and power and energy.

Django is an open-source Web framework and one of the more popular Python Web frameworks. This article mainly introduces how to connect, subscribe, unsubscribe, and send and receive messages between MQTT client and MQTT Broker in the Django project.

We will write a simple MQTT client using paho-mqtt client library. paho-mqtt is a widely used MQTT client library in Python that provides client support for MQTT 5.0, 3.1.1, and 3.1 on Python 2.7 and 3.x.

Project Initialization

This project uses Python 3.8 for development testing, and the reader can confirm the version of Python with the following command.

$ python3 --version
Python 3.8.2

Install Django and paho-mqtt using Pip.

pip3 install django
pip3 install paho-mqtt

Create a Django project.

django-admin startproject mqtt-test

The directory structure after creation is as follows.

└── mqtt_test

Using paho-mqtt

This article will use free public MQTT Broker provided by EMQ. The service is created based on MQTT Cloud service - EMQX Cloud. The server access information is as follows:

  • Broker:
  • TCP Port: 1883
  • Websocket Port: 8083

Open Manufacturing Hub
A Practical Guide to MQTT Broker Selection
Download this practical guide and learn what to consider when choosing an MQTT broker.
Get the eBook →

Import paho-mqtt

import paho.mqtt.client as mqtt

Writing connection callback

Successful or failed MQTT connections can be handled in this callback function, and this example will subscribe to the django/mqtt topic after a successful connection.

def on_connect(mqtt_client, userdata, flags, rc):
   if rc == 0:
       print('Connected successfully')
       print('Bad connection. Code:', rc)

Writing message callback

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}')

Adding Django configuration items

Add configuration items for the MQTT broker in Readers who have questions about the following configuration items and MQTT-related concepts mentioned in this article can 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_PORT = 1883

Configuring the MQTT client

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD)

Creating a message publishing API

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

import json
from django.http import JsonResponse
from mqtt_test.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

from django.urls import path
from . import views

urlpatterns = [
    path('publish', views.publish_message, name='publish'),

Start the MQTT client

Add the following code in

from . import mqtt

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 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 open-source cross-platform MQTT client - MQTTX to test connection, subscription, and publishing.

Test message receiving

  1. 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.

    Receive MQTT messages

  2. Publish the message Hello from MQTTX to the django/mqtt topic in the message publishing box at the bottom of MQTTX.

    Publish MQTT messages

  3. The messages sent by MQTTX will be visible in the Django runtime window.

    Run Django MQTT APP

Test message publishing API

  1. Subscribe to the django/mqtt topic in MQTTX.

    Subscribe to MQTT topic

  2. Use Postman to call /publish API: publish the message Hello from Django to the django/mqtt topic.

    Use Postman to call API

  3. You will see the messages sent by Django in MQTTX.

    Receive MQTT messages


At this point, we have completed the development of the MQTT client using paho-mqtt, enabling communication using MQTT in Django applications. In practice, we can extend the MQTT client to achieve more complex business logic based on business requirements.

Next, readers can check out The Easy-to-understand Guide to MQTT Protocol series of articles provided by EMQ to learn about MQTT protocol features, explore more advanced applications of MQTT, and get started with MQTT application and service development.

Try EMQX Cloud for Free
A fully managed MQTT service for IoT
Get Started →

Related Posts

May 27, 2022Ming
How to use MQTT in Flask

This article introduces how to use MQTT in the Flask project, and implement the connection, subscription and messaging, etc of MQTT.

Mar 3, 2024Dekun Tao
How to Use MQTT in Python with Paho Client

Learn to use MQTT in Python with Paho Client, the easy way! Our step-by-step tutorial will have you up and running in no time with this popular IoT protocol.

Aug 5, 2021Guowei Li
How to use MQTT in PHP

This article introduces how to use the "php-mqtt/client" client library in the PHP project, and implements connection, subscribe, messaging, etc of MQTT.