How to map a related object to a notification ============================================= Since django-nyt is based on Django, we encourage you to extend functionality by writing your own models. A common scenario is when you want to provide extra data with a notification. Typically, users are notified about a specific object being created or updated. You can keep this relation by writing your own relational model. For instance, if we want to track that a notification is for a specific Comment, we can store this relation in such a model: .. code-block:: python class CommentNotification(models.Model): notification = models.OneToOneField( "django_nyt.Notification", on_delete=models.CASCADE, related_name="comment", ) comment = models.ForeignKey( Comment, on_delete=models.CASCADE, ) Then we can plugin a Django signal to create the notification and store the new relation: .. code-block:: python @receiver(post_save, sender=Comment) def event_published(**kwargs): comment = kwargs.get("comment") # Notify everyone except for the comment author (they know!) notifications = notify( f"Comment created {comment.title}", key=COMMENT_CREATED, url=reverse("comments:comment_detail", kwargs={"pk": comments.id}), filter_exclude={"settings__user": comment.author}, ) for notification in notifications: models.CommentNotification.objects.create( notification=notification, comment=comment, ) After this, we can access the comment related to a notifications. For instance, if we have defined a custom template for the ``COMMENT_CREATED`` key, we could send out an email to a moderator and display the whole comment text in the email. Emails generated by django-nyt all receive their notifications in the template context, and therefore accessing the comments can be done with ``notification.comment`` (defined by the reverse relation on the ``OneToOneField``.) Notes on security ----------------- If a user has certain credentials in your system that are revoked at a later time, then they may still gain access through a relation by accessing a previous notification. As you may choose to revoke certain access, you should always design your system to anticipate this. It's therefore important that you deal with these relations in a sensible manner: * Delete relations when credentials are revoked * Do not use relations to display sensitive information or grant access