Django Push Notifications

3.3.0 · active · verified Thu Apr 16

django-push-notifications is a Django library for sending push notifications to mobile devices via services like FCM (Firebase Cloud Messaging), APNS (Apple Push Notification service), and to WebPush-enabled browsers (Chrome, Firefox, Opera). It simplifies device registration and message sending within a Django project. The current version is 3.3.0, and the project maintains an active release cadence with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure settings, register devices, and send notifications using both FCM (Firebase Cloud Messaging, via GCMDevice) and APNS (Apple Push Notification service) models. Note: The `settings.configure` and `apps.populate` lines are for running this example script standalone. In a typical Django project, you'd configure `settings.py` and then directly import and use the device models.

import os
from django.conf import settings
from django.apps import apps
from push_notifications.models import GCMDevice, APNSDevice

# --- Minimal Django settings for standalone execution ---
# In a real Django project, these settings would be in your settings.py
# and you would simply import and use the Device models after Django is initialized.
if not apps.ready:
    settings.configure(
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'push_notifications'
        ],
        # Minimal database settings for demo
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
        PUSH_NOTIFICATIONS_SETTINGS={
            "APNS_AUTH_KEY_PATH": os.environ.get("APNS_AUTH_KEY_PATH", "/path/to/apns_key.p8"),
            "APNS_AUTH_KEY_ID": os.environ.get("APNS_AUTH_KEY_ID", "YOUR_APNS_KEY_ID"),
            "APNS_TEAM_ID": os.environ.get("APNS_TEAM_ID", "YOUR_APNS_TEAM_ID"),
            "APNS_APP_ID": os.environ.get("APNS_APP_ID", "com.example.app"),
            "GCM_API_KEY": os.environ.get("GCM_API_KEY", "YOUR_LEGACY_FCM_SERVER_KEY"), # For legacy GCM
            "FCM_API_KEY": os.environ.get("FCM_API_KEY", "/path/to/fcm_v1_credentials.json"), # For FCM v1
        },
        DEFAULT_AUTO_FIELD='django.db.models.BigAutoField', # Recommended for Django 3.2+
    )
    apps.populate(settings.INSTALLED_APPS)
# --- End of minimal Django settings ---

print("Registering a GCM (FCM) device and sending a message...")
# Replace 'your_fcm_device_token' with an actual device token
device_gcm, created_gcm = GCMDevice.objects.get_or_create(
    registration_id="your_fcm_device_token",
    active=True,
    user=None # Link to a Django User object if applicable
)

if created_gcm:
    print(f"Created new GCM device: {device_gcm}")
else:
    print(f"Found existing GCM device: {device_gcm}")

try:
    response_gcm = device_gcm.send_message(
        "Hello from FCM!",
        badge=1,
        extra={"custom_data": "value"}
    )
    print(f"FCM message sent. Response: {response_gcm}")
except Exception as e:
    print(f"Error sending FCM message: {e}")

print("\nRegistering an APNS device and sending a message...")
# Replace 'your_apns_device_token' with an actual device token
device_apns, created_apns = APNSDevice.objects.get_or_create(
    registration_id="your_apns_device_token",
    active=True,
    user=None
)

if created_apns:
    print(f"Created new APNS device: {device_apns}")
else:
    print(f"Found existing APNS device: {device_apns}")

try:
    response_apns = device_apns.send_message(
        message="Hello from APNS!",
        badge=1,
        sound="default",
        category="my_category",
        mutable_content=1, # Note: integer 1 or 0 for >=3.2.1
        extra={"custom_data": "value"}
    )
    print(f"APNS message sent. Response: {response_apns}")
except Exception as e:
    print(f"Error sending APNS message: {e}")

# For WebPush, you would typically handle subscription via JavaScript in the frontend
# and then create/use a WebPushDevice instance similarly to send notifications.

view raw JSON →