Backend Development
Python Tutorial
Winning the Battle Against User Disengagement with Django Push Notifications
Winning the Battle Against User Disengagement with Django Push Notifications

In the fast-paced world of mobile apps, keeping users engaged is a challenge. Today, we explore how Django can help developers combat user disengagement by setting up push notifications to keep users informed and connected.
Setting Up Push Notifications in Django
Push notifications are like a friendly reminder, bringing users back to your app with updates or alerts. Django can handle this effectively with a few essential steps.
Step 1: Build a Notification Model
To get started, Django needs a notification model. This model will store all the notifications your app sends to users.
from django.db import models
from django.utils.translation import gettext_lazy as _
class Notification(models.Model):
title = models.CharField(max_length=255, verbose_name=_('Notification title'))
body = models.TextField(verbose_name=_('Notification body'))
image = models.ImageField(upload_to='notifications/', null=True, blank=True)
created_date = models.DateTimeField(auto_now_add=True) # Add this field
def __str__(self):
return self.title
class Meta:
ordering = ("-created_date",) # Now created_date exists
verbose_name = _('Notification')
Step 2: Creating a Send Notification Function
Next, we’ll add a function to send these notifications. This is where we write the logic that sends the message when needed, ensuring users get real-time updates.
#notifcations.py
import os
from google.oauth2 import service_account
from google.auth.transport.requests import Request
import requests
def refresh_access_token(service_account_file):
credentials = service_account.Credentials.from_service_account_file(
service_account_file,
scopes=["https://www.googleapis.com/auth/cloud-platform"],
)
credentials.refresh(Request())
access_token = credentials.token
return access_token
Step 3: Setting Up Signals
Django can use signals to trigger notifications based on user actions, like a new message or a completed task.
from django.db.models.signals import post_save
from django.dispatch import receiver
import requests
# Import the Notification model and the refresh_access_token function
from my_app.models import Notification # Change 'my_app' to your actual app name
from my_app.notifications import refresh_access_token # Update the path if necessary
@receiver(post_save, sender=Notification)
def send_notification_on_creation(instance, created, **kwargs):
if created:
service_account_file = '/home/rv/Documents/rv/push_notification/core/my_app/test-project.json'
tkn = refresh_access_token(service_account_file)
print('tkn',tkn)
endpoint = "https://fcm.googleapis.com/v1/projects/test-project-595ae/messages:send"
access_token = tkn
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
data = {
"message": {
"token":"dnTB_cv9TZ25jsOkkQSS0x:APA91bEghK69zhqpTi2B5hPFtX0mpLSzdSQswrGEKl60PrUQDgy9RTIc_f9pjfxoyuUU-w8xjwk0WO1KtvbwF3bYFlQ21HWv-JueS-Fu7azhUsjgULDN41TTTiqONsqLsbIqS9_xKsUv",
"notification": {
"title": instance.title,
"body": instance.body,
}
}
}
response = requests.post(endpoint, json=data, headers=headers)
if response.status_code == 200:
print("Push notification successfully sent!")
else:
print(f"Failed to send push notification. Status code: {response.status_code}")
print(response.text)
Step 4: Register in the Admin
Finally, by registering the notification model in the Django admin panel, we can manage notifications easily, keeping everything organized and ready.
from django.contrib import admin from .models import * admin.site.register(Notification)
Integrating Firebase for Frontend Notifications
To make sure notifications reach users’ devices, Django partners with Firebase.
The above is the detailed content of Winning the Battle Against User Disengagement with Django Push Notifications. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1386
52
How to solve the permissions problem encountered when viewing Python version in Linux terminal?
Apr 01, 2025 pm 05:09 PM
Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...
How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python?
Apr 01, 2025 pm 11:15 PM
When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...
How to teach computer novice programming basics in project and problem-driven methods within 10 hours?
Apr 02, 2025 am 07:18 AM
How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...
How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?
Apr 02, 2025 am 07:15 AM
How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...
What are regular expressions?
Mar 20, 2025 pm 06:25 PM
Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.
How does Uvicorn continuously listen for HTTP requests without serving_forever()?
Apr 01, 2025 pm 10:51 PM
How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...
What are some popular Python libraries and their uses?
Mar 21, 2025 pm 06:46 PM
The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H
How to dynamically create an object through a string and call its methods in Python?
Apr 01, 2025 pm 11:18 PM
In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...


