django_nyt package

Subpackages

Submodules

django_nyt.admin module

class NotificationAdmin(model, admin_site)

Bases: ModelAdmin

property media
raw_id_fields = ('user', 'subscription')
class SettingsAdmin(model, admin_site)

Bases: ModelAdmin

list_display = ('user', 'interval')
property media
raw_id_fields = ('user',)
class SubscriptionAdmin(model, admin_site)

Bases: ModelAdmin

display_interval(instance)
display_user(instance)
list_display = ('display_user', 'notification_type', 'display_interval')
property media
raw_id_fields = ('settings',)

django_nyt.apps module

class DjangoNytConfig(app_name, app_module)

Bases: AppConfig

name = 'django_nyt'
verbose_name = 'Django Nyt'

django_nyt.conf module

These are the available settings, accessed through django_nyt.conf.app_settings. All attributes prefixed NYT_* can be overridden from your Django project’s settings module by defining a setting with the same name.

For instance, to enable the admin, add the following to your project settings:

NYT_ENABLE_ADMIN = True
class AppSettings(NYT_DB_TABLE_PREFIX: str = 'nyt', NYT_ENABLE_ADMIN: bool = False, NYT_SEND_EMAILS: bool = True, NYT_EMAIL_SUBJECT: str = None, NYT_EMAIL_SENDER: str = 'notifications@example.com', NYT_EMAIL_TEMPLATE_DEFAULT: str = 'notifications/emails/default.txt', NYT_EMAIL_SUBJECT_TEMPLATE_DEFAULT: str = 'notifications/emails/default_subject.txt', NYT_EMAIL_TEMPLATE_NAMES: dict = <factory>, NYT_EMAIL_SUBJECT_TEMPLATE_NAMES: dict = <factory>, NYT_INTERVALS: list[tuple[int, typing.Any]] | tuple[tuple[int, typing.Any]] = ((0, 'instantly'), (1380, 'daily'), (9660, 'weekly')), NYT_INTERVALS_DEFAULT: int = 0, NYT_USER_MODEL: str = 'auth.User', NYT_ENABLE_CHANNELS: str = False, NYT_NOTIFICATION_CHANNEL: str = 'nyt_all-{notification_key:s}')

Bases: object

Access this instance as django_nyt.conf.app_settings.

NYT_DB_TABLE_PREFIX: str = 'nyt'

The table prefix for tables in the database. Do not change this unless you know what you are doing.

NYT_EMAIL_SENDER: str = 'notifications@example.com'

Default sender email for notification emails. You should definitely make this match an email address that your email gateway will allow you to send from. You may also consider a no-reply kind of email if your notification system has a UI for changing notification settings.

NYT_EMAIL_SUBJECT: str = None

Hard-code a subject for all emails sent (overrides the default subject templates).

NYT_EMAIL_SUBJECT_TEMPLATE_DEFAULT: str = 'notifications/emails/default_subject.txt'

Default template used for rendering the email subject. Should contain a valid template name. If a lookup in NYT_EMAIL_SUBJECT_TEMPLATE_NAMES doesn’t return a result, this fallback is used.

NYT_EMAIL_SUBJECT_TEMPLATE_NAMES: dict

Default dictionary, mapping notification keys to template names. The templates are used to generate a single-line email subject. Can be overwritten by database values. Keys can have a glob pattern, like USER_* or user/*.

When notification emails are generated, they are grouped by their templates such that notifications sharing the same template can be sent in a combined email.

Example:

NYT_EMAIL_SUBJECT_TEMPLATE_NAMES = OrderedDict(
    [
        ("admin/product/created", "myapp/notifications/email/admin_product_added.txt"),
        ("admin/**", "myapp/notifications/email/admin_default.txt"),
    ]
)
NYT_EMAIL_TEMPLATE_DEFAULT: str = 'notifications/emails/default.txt'

Default template used for rendering email contents. Should contain a valid template name. If a lookup in NYT_EMAIL_TEMPLATE_NAMES doesn’t return a result, this fallback is used.

NYT_EMAIL_TEMPLATE_NAMES: dict

Default dictionary, mapping notification keys to template names. Can be overwritten by database values. Keys can have a glob pattern, like USER_* or user/*.

When notification emails are generated, they are grouped by their templates such that notifications sharing the same template can be sent in a combined email.

Example:

NYT_EMAIL_TEMPLATE_NAMES = OrderedDict(
    [
        ("admin/product/created", "myapp/notifications/email/admin_product_added.txt"),
        ("admin/**", "myapp/notifications/email/admin_default.txt"),
    ]
)
NYT_ENABLE_ADMIN: bool = False

Enable django-admin registration for django-nyt’s ModelAdmin classes.

NYT_ENABLE_CHANNELS: str = False

Channels are enabled automatically when ‘channels’ application is installed, however you can explicitly disable it with NYT_CHANNELS_DISABLE.

NYT_INTERVALS: list[tuple[int, Any]] | tuple[tuple[int, Any]] = ((0, 'instantly'), (1380, 'daily'), (9660, 'weekly'))

List of intervals available for user selections. In minutes

NYT_INTERVALS_DEFAULT: int = 0

Default selection for new subscriptions

NYT_NOTIFICATION_CHANNEL: str = 'nyt_all-{notification_key:s}'
NYT_SEND_EMAILS: bool = True

Email notifications global setting, can be used to globally switch off emails, both instant and scheduled digests. Remember that emails are sent with python manage.py notifymail.

NYT_USER_MODEL: str = 'auth.User'

The swappable user model of Django Nyt. The default is to use the contents of AUTH_USER_MODEL.

django_nyt.consumers module

django_nyt.decorators module

data2jsonresponse(data, **kwargs)
disable_notify(f)

Disable notifications.

Does not work for async stuff, only disables notify in the same process.

Example:

@disable_notify
def your_function():
    notify("no one will be notified", ...)
json_view(f)
login_required_ajax(f)

Similar to login_required. But if the request is an ajax request, then it returns an error in json with a 403 status code.

django_nyt.forms module

class SettingsForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None)

Bases: ModelForm

class Meta

Bases: object

fields = ('interval', 'is_default')
model

alias of Settings

base_fields = {'interval': <django.forms.fields.TypedChoiceField object>, 'is_default': <django.forms.fields.BooleanField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

django_nyt.models module

class Notification(id, subscription, user, message, url, is_viewed, is_emailed, created, modified, occurrences)

Bases: Model

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

classmethod create_notifications(key, object_id=None, content_type=None, filter_exclude=None, recipient_users=None, **kwargs)

Creates notifications directly in database – do not call directly, use django_nyt.notify(…)

This is now an internal interface.

created

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)
get_next_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=True, **kwargs)
get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)
get_previous_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

is_emailed

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

is_viewed

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

latest_for

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

message

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

modified

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
occurrences

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

save(*args, **kwargs)

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

subscription

Either set the subscription

subscription_id
url

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

user_id
class NotificationType(*args, **kwargs)

Bases: Model

Notification types are added on-the-fly by the applications adding new notifications

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

content_type

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

content_type_id
classmethod get_by_key(key, content_type=None)
get_email_subject_template_name()
get_email_template_name()
key

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

label

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
subscription_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class Settings(*args, **kwargs)

Bases: Model

Reusable settings object for a subscription

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

created

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

classmethod get_default_setting(user)
classmethod get_default_settings(user)
get_interval_display(*, field=<django.db.models.fields.SmallIntegerField: interval>)
get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)
get_next_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=True, **kwargs)
get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)
get_previous_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

interval

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

is_default

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

modified

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
save(*args, **kwargs)

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

subscription_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

user_id
class Subscription(id, settings, notification_type, object_id, send_emails, latest, created, modified, last_sent)

Bases: Model

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

created

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

get_next_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=True, **kwargs)
get_next_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=True, **kwargs)
get_previous_by_created(*, field=<django.db.models.fields.DateTimeField: created>, is_next=False, **kwargs)
get_previous_by_modified(*, field=<django.db.models.fields.DateTimeField: modified>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

last_sent

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

latest

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

latest_id
modified

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

notification_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

notification_type

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

notification_type_id
object_id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
send_emails

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

settings

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

settings_id
clear_notification_type_cache(*args, **kwargs)

django_nyt.routing module

django_nyt.subscribers module

django_nyt.urls module

get_pattern(app_name='nyt', namespace='nyt')

Every url resolution takes place as “nyt:view_name”. https://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-reversing-url-namespaces

django_nyt.utils module

notify(message: str, key: str, target_object: Any = None, url: str = None, filter_exclude: dict = None, recipient_users: list = None) List[Notification]

Notify subscribing users of a new event. Key can be any kind of string, just make sure to reuse it where applicable.

Here is the most basic example: Everyone subscribing to the “new_comments” key are sent a notification with the message “New comment posted”:

notify("New comment posted", "new_comments")

Here is an example that will create a Notification object for everyone who has a subscription for the key “comment/response” and the model instance comment_instance. The idea would be that the poster of comment_instance will receive notifications when someone responds to that comment.

notify(
    "there was a response to your comment",
    "comment/response",
    target_object=comment_instance,
    url=reverse('comments:view', args=(comment_instance.id,))
)
Parameters:
  • message – A string containing the message that should be sent to all subscribed users.

  • key – A key object which is matched to NotificationType.key. Users with a Subscription for that NotificationType will have a Notification object created.

  • url – A URL pointing to your notification. If the URL is pointing to your Django project’s unique website, then add an /absolute/url. However, if the URL should take the user to a different website, use a full HTTP scheme, i.e. https://example.org/url/.

  • recipient_users – A possible iterable of users that should be notified instead of notifying all subscribers of the event. Notice that users still have to be actually subscribed to the event key!

  • target_object – Any Django model instance that this notification relates to. Uses Django content types. Subscriptions with a matching content_type and object_id will be notified.

  • filter_exclude – Keyword arguments passed to filter out Subscriptions. Will be handed to Subscription.objects.exclude(**filter_exclude).

subscribe(settings: Settings, key: str, content_type: str | ContentType = None, object_id: int | str = None, **kwargs) Subscription

Creates a new subscription to a given key. If the key does not exist as a NotificationType, it will be created

Uses get_or_create to avoid double creation.

Parameters:
  • settings – A models.Settings instance

  • key – The unique key that the Settings should subscribe to

  • content_type – If notifications are regarding a specific ContentType, it should be set

  • object_id – If the notifications should only regard a specific object_id

  • **kwargs

    Additional models.Subscription field values

unsubscribe(key: str, user: Any = None, settings: Settings = None, content_type: str | ContentType = None, object_id: int | str = None) Tuple[int, dict]

Shortcut function to remove all subscriptions related to a notification key and either a user or a settings object.

Unsubscribing does NOT delete old notifications, however the subscription relation is nullified. This means that any objects accessed through that relation will become inaccessible. This is a particular feature chosen to avoid accidentally allowing access to data that may be otherwise have credential-based access.

Parameters:
  • key – The notification key to unsubscribe a user/user settings.

  • user – User to unsubscribe

  • settings – …or a UserSettings object

  • content_type – Further narrow down subscriptions to only this content_type

  • object_id – Further narrow down subscriptions to only this object_id (provided a content_type)

Returns:

(int, dict) - the return value of Django’s queryset.delete() method.

django_nyt.views module

get_notifications(request, latest_id=None, is_viewed=False, max_results=10)

View that returns a JSON list of notifications for the current user as according to request.user.

Param:

latest_id: The latest id of a notification. Use this to avoid

retrieving the same notifications multiple times. :param: is_viewed: Set this to True if you also want to retrieve notifications that have already been viewed.

Returns:

An HTTPResponse object with JSON data:

{'success': True,

’total_count’: total_count, ‘objects’: [{‘pk’: n.pk,

’message’: n.message, ‘url’: n.url, ‘occurrences’: n.occurrences, ‘occurrences_msg’: _(‘%d times’) % n.occurrences, ‘type’: n.subscription.notification_type.key if n.subscription else None, ‘since’: naturaltime(n.created)} for n in notifications[:max_results]]}

goto(request, notification_id=None)
mark_read(request, id_lte, notification_type_id=None, id_gte=None)

Module contents