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.
Top comments (0)