'Design question: Is there a Django specific way to select users to receive notifications when a form is submitted?

I have a Django app, and need to send email notifications to certain users at certain points in my processes without adding any external libraries. For example, if any user submits a particular form, I need to send a notification to a specific set of users.

I'm thinking to use custom model permissions for each model that relates to a particular form. Then hypothetically add users to unique Authentication Groups that have those particular permissions.

Then I would create a Notifier class with a notify_users_by_email method that could accept an authorization group and a reason type. Have each reason type be 1-to-1 with the permissions defined at the model level. Then we can just filter the group to the users in the group and send the email.

I would also add a Notifications model, which could be used to record who sent the notifications, who was the intended recipient, send time and the notification reason (again related to permission).

In general, is that an appropriate way of going about this, or is there a cleaner way to do this in Django?

class Notifier:

    @classmethod
    def notify_group_by_email(cls, group_id: int, reason: str):
        users_in_group = Group.objects.get(id=group_id).user_set.all()
        for user in users_in_group:
            cls.notify_user_by_email(user_id=user.id, reason=reason)
            user = User.objects.get(id=user.id)
            email_string = f"{user.username}@gmail.com"
            print(f"Notified user {email_string} re: {reason}")

    @classmethod
    def notify_user_by_email(cls, reason: str, user_id: int):
        assert isinstance(reason, str)
        assert isinstance(user_id, int)

Notification class:

class Notification(DateUserFieldsAbstract):
    id = models.BigAutoField(
        auto_created=True,
        primary_key=True,
        serialize=False,
        verbose_name='ID')
    sender_id = models.ForeignKey('User', on_delete=models.PROTECT)
    receiver_id = models.ForeignKey('User', on_delete=models.PROTECT)
    reason = models.CharField(max_length=100)
    type = models.CharField(max_length=100)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source