question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Custom Notification Model field not created on notify.send

See original GitHub issue

Hi, I am trying to add a new field to the Notification model. Currently in my main/models.py i have:

class Notification(AbstractNotification):
    # custom field example
    unique_uuid = models.CharField(max_length=255,unique=True, null=True)

    class Meta(AbstractNotification.Meta):
        abstract = False
        app_label = 'main'

Now in my settings.py file I have:

NOTIFICATIONS_NOTIFICATION_MODEL = 'main.Notification'
NOTIFICATIONS_USE_JSONFIELD=True

I am trying to generate a notification in my views.py by using:

notify.send(sender=user, recipient=post.author, verb=message, target=post, \
                        unique_uuid = notification_create_uuid(...))

However, the notification is not being created correctly and the field is returning “None”. How can I set this field in notify.send(), so that the notification is created with that field set?

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:4
  • Comments:8

github_iconTop GitHub Comments

2reactions
gmverdoncommented, Mar 30, 2022

Can this PR please be merged? @pandafy

0reactions
Whatislove118commented, Aug 17, 2022

A quick and dirty hack might be to put in your models.py the following (it’s coming from base/models.py inside the notifications package, modified it a bit, and disconnected the original notify_handler.) :

from notifications.base.models import AbstractNotification
from distutils.version import StrictVersion
from django import get_version
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models.query import QuerySet
from django.utils import timezone
from jsonfield.fields import JSONField
from model_utils import Choices

from notifications import settings as notifications_settings
from notifications.signals import notify
from notifications.utils import id2slug
from swapper import load_model

if StrictVersion(get_version()) >= StrictVersion('1.8.0'):
    from django.contrib.contenttypes.fields import GenericForeignKey  # noqa
else:
    from django.contrib.contenttypes.generic import GenericForeignKey  # noqa

from notifications.models import notify_handler

EXTRA_DATA = notifications_settings.get_config()['USE_JSONFIELD']


class Notification(AbstractNotification):
    # custom field example
    example_field = models.BooleanField(default=False)

    class Meta(AbstractNotification.Meta):
        abstract = False

def notify_handler_custom(verb, **kwargs):
    """
    Handler function to create Notification instance upon action signal call.
    """
    # Pull the options out of kwargs
    kwargs.pop('signal', None)
    recipient = kwargs.pop('recipient')
    actor = kwargs.pop('sender')
    optional_objs = [
        (kwargs.pop(opt, None), opt)
        for opt in ('target', 'action_object')
    ]
    public = bool(kwargs.pop('public', True))
    description = kwargs.pop('description', None)
    example_field = kwargs.pop('example_field', None)
    timestamp = kwargs.pop('timestamp', timezone.now())
    Notification = load_model('notifications', 'Notification')
    level = kwargs.pop('level', Notification.LEVELS.info)
    # Check if User or Group
    if isinstance(recipient, Group):
        recipients = recipient.user_set.all()
    elif isinstance(recipient, (QuerySet, list)):
        recipients = recipient
    else:
        recipients = [recipient]
    new_notifications = []
    for recipient in recipients:
        newnotify = Notification(
            recipient=recipient,
            actor_content_type=ContentType.objects.get_for_model(actor),
            actor_object_id=actor.pk,
            verb=str(verb),
            public=public,
            description=description,
            example_field=example_field,
            timestamp=timestamp,
            level=level,
        )
        # Set optional objects
        for obj, opt in optional_objs:
            if obj is not None:
                setattr(newnotify, '%s_object_id' % opt, obj.pk)
                setattr(newnotify, '%s_content_type' % opt,
                        ContentType.objects.get_for_model(obj))
        if kwargs and EXTRA_DATA:
            newnotify.data = kwargs
        newnotify.save()
        new_notifications.append(newnotify)
    return new_notifications

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

The only things you have to change if i’m not mistaken is :

  • example_field (2 occurences, ctrl+f it)
  • dispatch_uid=‘your_app.models.notification’ on the connect. Change ‘your_app’ with… well your app name I guess.

Once you stop and restart the server it will work (if you have made your makemigrations and migrate, obviously). (At least in my case it worked.)

Thx, it really works 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Conflict model when create custom Notification inherit from ...
The original Notification model is swappable, if you have configured NOTIFICATIONS_NOTIFICATION_MODEL settings properly, it should work ...
Read more >
IntegrityError while trying to send a notification with django ...
Ok, I found the problem. For some reason south was using InnoDB storage engine as a default while all my tables have MyISAM...
Read more >
Notification::send with non-existing user model - Laracasts
Hi, Is it possible to send a notification to a non-existing user model? ... So for the custom email addresses I created a...
Read more >
Manage Your Notifications with Notification Builder
Create custom notifications to give your users new information and reminders. Choose whether Salesforce notifications appear on desktop, mobile, Slack, or at ...
Read more >
How to set up user notifications for your Django app - Part 1
We added business logic to create a notification instance whenever the signal is received. notify.send is a signal provided by the Django- ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found