Skip to main content

django-notifications (community fork)

tests PyPI Python versions Django versions

This is a community-maintained fork of django-notifications/django-notifications.

The original project appears unmaintained: version 1.9.0 (with Django 5.x and Python 3.13 support) has been sitting unreleased on master, and requests for PyPI and maintainer access have gone unanswered. See the discussion in upstream issue #416 for context.

All credit for the original work goes to Justin Quick, Yang Yubo, and the django-notifications team (see AUTHORS.txt). This fork exists solely to continue shipping releases to PyPI and keep the project compatible with current Django and Python versions. If upstream resumes active maintenance, we will happily coordinate and, where appropriate, redirect users back.

Drop-in replacement. The Python import path is unchanged (import notifications). To switch from the original package:

pip uninstall django-notifications-hq
pip install django-notifications-community

or with uv:

uv remove django-notifications-hq
uv add django-notifications-community

Editing pyproject.toml by hand and running uv sync can leave the shared notifications/ import path in a half-installed state, since both distributions write to the same directory. Use uv remove + uv add (or uv pip install --reinstall django-notifications-community as a fallback) to avoid it.

Contents

Overview

django-notifications is a GitHub-style notifications app for Django, derived from django-activity-stream.

The major difference between django-notifications and django-activity-stream:

  • django-notifications is for building something like GitHub "Notifications".
  • django-activity-stream is for building a GitHub "News Feed".

A notification is an action event, categorized by four components:

  • Actor — the object that performed the activity.
  • Verb — the verb phrase that identifies the action.
  • Action Object — (optional) the object linked to the action itself.
  • Target — (optional) the object the activity was performed on.

Actor, Action Object, and Target are GenericForeignKeys to any arbitrary Django object. An action describes something that was performed (Verb) at some instant in time by an Actor on an optional Target, resulting in an Action Object being created, updated, or deleted.

For example: justquick (actor) closed (verb) issue 2 (action_object) on activity-stream (target) 12 hours ago.

Nomenclature is based on the Activity Streams spec: https://activitystrea.ms/specs/atom/1.0/.

Requirements

  • Python 3.10, 3.11, 3.12, 3.13, 3.14
  • Django 5.2, 6.0, 6.1 (Django 6.0 and later require Python 3.12+)

If you need Django 4.2 or 5.1, pin django-notifications-community<1.12.

If you need Python 3.9, pin django-notifications-community<1.10.

Installation

Install with pip:

pip install django-notifications-community

or with uv:

uv add django-notifications-community

Add notifications to INSTALLED_APPS. It depends on django.contrib.auth and django.contrib.contenttypes (both ship in the default Django project):

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    ...
    'notifications',
    ...
]

Include the notifications URLs in your urlconf:

urlpatterns = [
    ...
    path('inbox/notifications/', include('notifications.urls', namespace='notifications')),
    ...
]

Run the migrations:

python manage.py migrate notifications

Settings

All configuration lives in a single DJANGO_NOTIFICATIONS_CONFIG dict in settings.py. Defaults:

DJANGO_NOTIFICATIONS_CONFIG = {
    'PAGINATE_BY': 20,
    'USE_JSONFIELD': False,
    'SOFT_DELETE': False,
    'NUM_TO_FETCH': 10,
    'CACHE_TIMEOUT': 2,
    'API_EXCLUDED_FIELDS': (),
}
Key Default Purpose
PAGINATE_BY 20 Page size for the list views.
USE_JSONFIELD False Persist extra kwargs passed to notify.send() on Notification.data.
SOFT_DELETE False Flip the delete view from row removal to setting deleted=True. See Soft delete.
NUM_TO_FETCH 10 Default page size for the live-updater JSON endpoints.
CACHE_TIMEOUT 2 Seconds to cache user.notifications.unread().count. 0 disables caching.
API_EXCLUDED_FIELDS () Extra model fields to keep out of the JSON endpoints. See Live-updater API.

Extra data

Extra keyword arguments passed to notify.send(...) are split by name. A kwarg matching a concrete field on the notification model is assigned to that field. Everything else is extra data.

With USE_JSONFIELD on, the leftover kwargs are stored on the notification's .data attribute, JSON serialized. Pass only JSON-serializable values. With it off, they are dropped. Custom model fields are assigned either way, since they do not depend on the JSON field.

Soft delete

With SOFT_DELETE on, delete/<int:slug>/ flips Notification.deleted to True instead of removing the row. The unread and read querysets gain a deleted=False filter, and the deleted, active, mark_all_as_deleted, and mark_all_as_active queryset methods become usable. See QuerySet methods below.

Multi-site

If you serve more than one site from the same Django project (different domains or SITE_IDs), install the companion package django-notifications-community-sites to scope notifications to the current site. The cleanest way is via the sites extra:

pip install "django-notifications-community[sites]"

That pulls the companion in automatically. See its README for the rest of the setup (an extra app in INSTALLED_APPS, the NOTIFICATIONS_NOTIFICATION_MODEL setting, and SITE_ID).

The companion plugs into the extension hooks added in 1.12.0 (notifications.registry), so views, helpers, and template tags pick up site scoping without any change to your code or templates here.

Generating notifications

The typical pattern is to send a notification from a signal handler on one of your own models:

from django.db.models.signals import post_save
from notifications.signals import notify
from myapp.models import MyModel

def my_handler(sender, instance, created, **kwargs):
    notify.send(instance, verb='was saved')

post_save.connect(my_handler, sender=MyModel)

You can also call notify.send() directly anywhere in your code:

from notifications.signals import notify

notify.send(user, recipient=user, verb='you reached level 10')

Note: notify.send() uses bulk_create internally, so post_save handlers registered on the Notification model itself will not fire. See Bulk creation and signals.

Full signature:

notify.send(
    actor, recipient, verb,
    action_object, target,
    level, description, public, timestamp,
    **kwargs,
)

Arguments:

  • actor (required) — any object. Use sender instead of actor if you're passing keyword arguments.
  • recipient (required) — a single User, a Group, a User queryset, or a list of Users.
  • verb (required) — a string.
  • action_object — any object.
  • target — any object.
  • level — one of Notification.LEVELS ('success', 'info', 'warning', 'error'). Defaults to 'info'.
  • description — a string.
  • public — a bool. Defaults to True.
  • timestamp — a datetime. Defaults to timezone.now().

QuerySet and model methods

QuerySet methods

The Notification manager is built from a custom QuerySet via Django's QuerySet.as_manager(), so queryset methods are available on the manager, on related managers, and on any further-filtered queryset:

Notification.objects.unread()

user = User.objects.get(pk=pk)
user.notifications.unread()

Available methods:

Method Purpose
qs.unread() Unread notifications. With SOFT_DELETE=True, excludes deleted.
qs.read() Read notifications. With SOFT_DELETE=True, excludes deleted.
qs.unsent() emailed=False.
qs.sent() emailed=True.
qs.mark_all_as_read([recipient]) Mark all unread rows as read.
qs.mark_all_as_unread([recipient]) Mark all read rows as unread.
qs.mark_as_sent([recipient]) Mark unsent rows as sent.
qs.mark_as_unsent([recipient]) Mark sent rows as unsent.
qs.deleted() Rows with deleted=True. Requires SOFT_DELETE=True.
qs.active() Rows with deleted=False. Requires SOFT_DELETE=True.
qs.mark_all_as_deleted([recipient]) Flip to deleted=True. Requires SOFT_DELETE=True.
qs.mark_all_as_active([recipient]) Flip to deleted=False. Requires SOFT_DELETE=True.

Model methods

  • obj.timesince([datetime]) — wrapper around Django's timesince.
  • obj.naturalday() / obj.naturaltime() — wrappers around the django.contrib.humanize helpers of the same name.
  • obj.mark_as_read() / obj.mark_as_unread() — flip unread on a single row.
  • obj.slug — URL-safe encoded id, used by the mark-as-read, mark-as-unread, and delete views.

Template tags

Load the tag library in your template:

{% load notifications_tags %}

notifications_unread

{% notifications_unread %}

Returns the unread count for the current user, or an empty string for anonymous users. Storing it in a variable is usually what you want:

{% notifications_unread as unread_count %}
{% if unread_count %}
    You have <strong>{{ unread_count }}</strong> unread notifications.
{% endif %}

Live-updater API

A small JavaScript API periodically polls the server to keep unread counts and lists up to date. Two endpoints are provided for unread data:

  1. api/unread_count/ — {"unread_count": 1}
  2. api/unread_list/ — {"unread_count": 1, "unread_list": [ ... ]}

Matching api/all_count/ and api/all_list/ endpoints cover all notifications (read and unread) and follow the same key pattern — {scope}_count and {scope}_list, where scope mirrors the endpoint segment (so all_count, all_list).

Notification JSON follows the model's concrete fields, so any field you add to a swapped-in notification model shows up in the payload too. The recipient and the content type / object id columns behind the generic relations are left out: actor, target, and action_object are rendered as strings instead, and data is attached separately when it holds something. Two kinds of field are skipped, since neither survives JSON encoding: many to many fields, and file fields, which are reduced to their stored path.

Since custom fields land in the same dict, a field named slug, actor, target, action_object, data, or one of the _url keys below is overwritten by the value the package puts there. Name yours something else.

Following the model means a field you would rather keep private goes out with the rest. List those in API_EXCLUDED_FIELDS:

DJANGO_NOTIFICATIONS_CONFIG = {
    'API_EXCLUDED_FIELDS': ['moderation_note', 'internal_score'],
}

The endpoints are per user and require an authenticated request, so a field is only ever visible to the recipient. Worth a look anyway if you store something on the model that the recipient should not read back.

Each list entry also exposes target_url, actor_url, and action_object_url, which come from Model.get_absolute_url() by default. You can override the URL specifically for notifications by implementing Model.get_url_for_notifications(notification, request) on the related model.

Query string arguments (list endpoints):

  • max — maximum length of the returned list.
  • mark_as_read — if truthy, mark the returned notifications as read.

Example: GET api/unread_list/?max=3&mark_as_read=true returns three notifications and marks them read, so they'll drop off the next request.

Security note: the state-changing views (mark_as_read, mark_as_unread, mark_all_as_read, delete) require POST and a CSRF token. Only the list-with-mark_as_read query parameter above is accessible via GET, and it's gated to the requesting user's own unread rows.

Wiring it up

  1. Load {% load notifications_tags %} in the template.

  2. Include the JS and register the callbacks:

    <script src="{% static 'notifications/notify.js' %}"></script>
    {% register_notify_callbacks callbacks='fill_notification_list,fill_notification_badge' %}
    

    Since 1.11.2, register_notify_callbacks renders its configuration as a <script type="application/json"> block rather than inline JS, so it works under strict Content Security Policies without a 'unsafe-inline' allowance.

    register_notify_callbacks arguments:

    • badge_class (default live_notify_badge) — CSS class of the unread-count element.
    • menu_class (default live_notify_list) — CSS class of the list element.
    • refresh_period (default 15) — poll interval in seconds.
    • fetch (default 5) — how many notifications to fetch each poll.
    • callbacks (default '') — comma-separated list of JS functions to call on each poll.
    • api_name (default list) — either list or count.
    • mark_as_read (default False) — mark fetched notifications as read.
    • nonce (default None) — if set, emitted as the nonce attribute on the <script> tag, for strict CSP setups that allow JSON blocks by nonce.
  3. Insert a live-updating badge:

    {% live_notify_badge %}
    

    Takes badge_class (default live_notify_badge) — CSS class for the generated <span>.

  4. Insert a live-updating list:

    {% live_notify_list %}
    

    Takes list_class (default live_notify_list) — CSS class for the generated <ul>.

Using the live-updater with Bootstrap

Reuse the template tags with Bootstrap's classes:

{% live_notify_badge badge_class="badge" %}
{% live_notify_list list_class="dropdown-menu" %}

Custom JavaScript callbacks

The callbacks argument of register_notify_callbacks is a comma-separated list of JS function names called on every poll. Each function receives one argument, data, containing the entire API response.

{% register_notify_callbacks callbacks='fill_notification_badge,my_special_notification_callback' %}
function my_special_notification_callback(data) {
    for (const msg of data.unread_list) {
        console.log(msg);
    }
}

Testing the live-updater

  1. Clone the repo.
  2. Run python manage.py runserver.
  3. Browse to http://127.0.0.1:8000/test/.
  4. Click "Make a notification" — a new notification should appear in the list within 5-10 seconds.

Serializing the notification model

See the DRF guide on generic relationships. The example below picks a serializer based on the target type:

class GenericNotificationRelatedField(serializers.RelatedField):

    def to_representation(self, value):
        if isinstance(value, Foo):
            return FooSerializer(value).data
        if isinstance(value, Bar):
            return BarSerializer(value).data


class NotificationSerializer(serializers.Serializer):
    recipient = PublicUserSerializer(read_only=True)
    unread = serializers.BooleanField(read_only=True)
    target = GenericNotificationRelatedField(read_only=True)

Thanks to @DaWy.

AbstractNotification model

If you need to extend the notification model with extra fields, subclass AbstractNotification:

# your_app/models.py
from django.db import models
from notifications.base.models import AbstractNotification


class Notification(AbstractNotification):
    category = models.ForeignKey('myapp.Category', on_delete=models.CASCADE)

    class Meta(AbstractNotification.Meta):
        abstract = False

Then point the library at your model in settings.py:

NOTIFICATIONS_NOTIFICATION_MODEL = 'your_app.Notification'

Extra fields are populated by passing them to notify.send(). A foreign key takes either the instance or the raw primary key:

notify.send(actor, recipient=user, verb='commented', category=category)
notify.send(actor, recipient=user, verb='commented', category_id=category.pk)

As of 1.11.3, swapping is resolved via Django's built-in app loading rather than the third-party swapper package. No configuration changes are required when upgrading.

Notes

Email notifications

Email delivery is not built in. The Notification.emailed field is reserved to make it easier to track whether you've sent one.

Bulk creation and signals

As of 1.11.0, notify.send() uses bulk_create, which means Django's post_save signal does not fire for the Notification rows it writes.

If you previously relied on post_save to trigger side effects (email, push, etc.), switch to connecting the notify signal instead:

from notifications.signals import notify

def handle_notifications(sender, verb, **kwargs):
    recipient = kwargs.get('recipient')
    # side effect here (send email, push, ...)

notify.connect(handle_notifications)

The notify signal fires once per notify.send() call, before the rows are written. If you need access to the saved Notification objects, use the return value of notify.send() instead:

from notifications.signals import notify

responses = notify.send(
    sender=user,
    recipient=target_user,
    verb='commented on',
    target=post,
)

# Each response is a (handler_function, return_value) tuple.
# The default handler returns the list of created Notification objects.
for handler, notifications in responses:
    for notification in notifications:
        send_push(notification.recipient, str(notification))

Sample app

A sample app lives at notifications/tests/sample_notifications and exercises the AbstractNotification swap path. Run it by exporting SAMPLE_APP=1:

export SAMPLE_APP=1
python manage.py runserver
unset SAMPLE_APP

Credits

Upstream contributors

The original django-notifications was built by (alphabetical):

See AUTHORS.txt for the full contributor list.

Fork maintainers

This community fork is maintained by django-notifications-community contributors. Please use this repo's issue tracker for fork-specific bugs and features rather than contacting the upstream authors.

Contributing

See CONTRIBUTING.md for development setup, testing, and pull request guidelines.

Metadata

Release files for django-notifications-community 1.12.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-notifications-community 1.12.3
File Size Uploaded Provenance Actions
django_notifications_community-1.12.3.tar.gz 60.8 kB With provenance Details for django_notifications_community-1.12.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-notifications-community 1.12.3
File Interpreter ABI Platform Actions
django_notifications_community-1.12.3-py3-none-any.whl Python 3 none any Details for django_notifications_community-1.12.3-py3-none-any.whl

Total release size: 100.9 kB

Release files / django_notifications_community-1.12.3.tar.gz

Download URL django_notifications_community-1.12.3.tar.gz
Size 60.8 kB
Tags Source
SHA-256 checksum
How to use checksums
83e8b625b195551263ca08b0d46c7e42a1b6be8944ccdfcb9fce46489a3f3957
BLAKE2b-256 checksum
How to use checksums
10f48a296f58c46f601c11441659966103c4b47aa59ba98898d8eafef2aba6b3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 11, 2026.

Transparency log

Release files / django_notifications_community-1.12.3-py3-none-any.whl

Download URL django_notifications_community-1.12.3-py3-none-any.whl
Size 40.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8567da8ebca0770f6dd118ce5cc132a64147d9f876eff2406f06cc913336cd1a
BLAKE2b-256 checksum
How to use checksums
78663679256967eaf63e6b99111bc5ae5e2db46166d7bf174d7251079dbfb98d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 11, 2026.

Transparency log

Security for django-notifications-community 1.12.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_notifications_community-1.12.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 11, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page