CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-notifications-hq

GitHub notifications alike app for Django providing comprehensive activity tracking and notification features.

Pending
Overview
Eval results
Files

signals.mddocs/

Signal System

Django signal system for creating notifications with flexible actor-verb-object patterns. Supports individual users, groups, and querysets as recipients with automatic notification creation and handling.

Capabilities

Notification Signal

The main Django signal used to trigger notification creation with flexible recipient handling and optional object references.

from django.dispatch import Signal

notify = Signal()

Signal Handler Function

The core function that processes notification signals and creates notification instances with support for multiple recipient types and optional objects.

def notify_handler(verb, **kwargs):
    """
    Create Notification instances from signal calls.
    
    Args:
        verb (str): Action verb describing what happened
        **kwargs: Additional parameters for notification creation
        
    Required kwargs:
        recipient: User, Group, QuerySet, or list of Users to notify
        sender: Actor object that performed the action
        
    Optional kwargs:
        target: Target object the action was performed on
        action_object: Object linked to the action itself
        public (bool): Whether notification is public (default: True)
        description (str): Text description of the notification
        timestamp (datetime): Custom timestamp (default: now)
        level (str): Notification level (default: 'info')
        actor_for_concrete_model (bool): ContentType behavior (default: True)
        target_for_concrete_model (bool): ContentType behavior (default: True)
        action_object_for_concrete_model (bool): ContentType behavior (default: True)
        Additional kwargs stored in data JSONField if USE_JSONFIELD=True
        
    Returns:
        list: List of created Notification instances
        
    Raises:
        Various exceptions based on model validation and database constraints
    """

Usage Examples

Basic Notification Creation

from django.contrib.auth.models import User
from notifications.signals import notify

# Get users
actor = User.objects.get(username='john')
recipient = User.objects.get(username='jane')

# Send simple notification
notify.send(
    sender=actor,          # Required: who performed the action
    recipient=recipient,   # Required: who should be notified
    verb='followed',       # Required: what action was performed
    description='John started following you'
)

Notification with Target Object

from myapp.models import Post

post = Post.objects.get(id=1)

# Notify about action on target object
notify.send(
    sender=actor,
    recipient=post.author,  # Notify the post author
    verb='liked',
    target=post,           # The post that was liked
    description=f'{actor.username} liked your post "{post.title}"'
)

Notification with Action Object

from myapp.models import Comment

comment = Comment.objects.create(
    post=post,
    author=actor,
    content='Great post!'
)

# Notify about new comment (action object) on post (target)
notify.send(
    sender=actor,
    recipient=post.author,
    verb='commented on',
    action_object=comment,  # The comment that was created
    target=post,           # The post that was commented on
    description=f'{actor.username} commented on your post'
)

Multiple Recipients

# Notify multiple users individually
recipients = [user1, user2, user3]
notify.send(
    sender=actor,
    recipient=recipients,   # List of users
    verb='posted',
    target=post,
    description='New post available'
)

# Notify all users in a group
from django.contrib.auth.models import Group
editors = Group.objects.get(name='editors')
notify.send(
    sender=actor,
    recipient=editors,      # All users in group will be notified
    verb='submitted',
    target=post,
    description='New post submitted for review'
)

# Notify users from queryset
active_users = User.objects.filter(is_active=True)
notify.send(
    sender=actor,
    recipient=active_users,  # All active users
    verb='announced',
    description='System maintenance announcement'
)

Notification Levels and Additional Data

# Set notification level
notify.send(
    sender=actor,
    recipient=recipient,
    verb='failed to process',
    level='error',          # 'success', 'info', 'warning', 'error'
    description='Payment processing failed'
)

# Include additional data (requires USE_JSONFIELD=True)
notify.send(
    sender=actor,
    recipient=recipient,
    verb='earned',
    description='Achievement unlocked!',
    # Additional data stored in JSONField
    achievement_name='First Post',
    points_earned=100,
    badge_url='/static/badges/first-post.png'
)

Custom Timestamps and Visibility

from django.utils import timezone
from datetime import timedelta

# Custom timestamp
past_time = timezone.now() - timedelta(hours=2)
notify.send(
    sender=actor,
    recipient=recipient,
    verb='completed',
    timestamp=past_time,
    description='Task completed 2 hours ago'
)

# Private notification (not public)
notify.send(
    sender=actor,
    recipient=recipient,
    verb='sent private message',
    public=False,           # Only visible to recipient
    description='You have a private message'
)

Signal Connection

The signal handler is automatically connected when the app loads:

# Automatic connection in notifications/base/models.py
from notifications.signals import notify
from notifications.base.models import notify_handler

notify.connect(notify_handler, dispatch_uid='notifications.models.notification')

Using from App Ready Method

For consistent signal access, the notify signal is also available directly from the notifications module:

# Available after app is ready
import notifications
notifications.notify.send(
    sender=actor,
    recipient=recipient,
    verb='updated',
    description='Profile updated'
)

Error Handling

try:
    notify.send(
        sender=actor,
        recipient=recipient,
        verb='performed action',
        target=some_object
    )
except Exception as e:
    # Handle notification creation errors
    logger.error(f"Failed to create notification: {e}")
    # Application logic continues normally

Integration with Django Signals

from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import BlogPost

@receiver(post_save, sender=BlogPost)
def notify_blog_post_created(sender, instance, created, **kwargs):
    if created:
        # Notify followers when new blog post is created
        followers = instance.author.followers.all()
        if followers.exists():
            notify.send(
                sender=instance.author,
                recipient=followers,
                verb='published',
                target=instance,
                description=f'New blog post: {instance.title}'
            )

Install with Tessl CLI

npx tessl i tessl/pypi-django-notifications-hq

docs

admin-integration.md

api-endpoints.md

configuration.md

core-system.md

index.md

signals.md

template-integration.md

utilities.md

web-interface.md

tile.json