django-triggers
is intended for implementing event-based business logic configurable through the Django admin site.
pip install dj-triggers
INSTALLED_APPS = [
...
"polymorphic",
"triggers",
...
]
Celery is required to be setup in your project.
Let's consider a simple tasks app with a model Task
and we want to email a user when a task is completed.
- Add event, action and condition models into your app's models.py
By doing this, we separate the development of the trigger components from their configuration within the Django admin panel. This ensures a more modular and manageable approach to building and configuring triggers.
The full code example is available in tests directory.
from django.dispatch import receiver, Signal
from django.contrib.auth.models import User
from django.db import models, transaction
from triggers.models import Action, Event
# Our domain model
class Task(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=128)
is_completed = models.BooleanField(default=False, db_index=True, editable=False)
is_important = models.BooleanField(default=False)
completed = Signal()
def complete(self):
if not self.is_completed:
self.is_completed = True
self.save()
transaction.on_commit(lambda: self.completed.send(sender=self.__class__, task=self))
# At first, implement an Event which will trigger the notification.
class TaskCompletedEvent(Event):
# By setting the following `important_only` field through the Django admin site
# we can configure what tasks (all or important only) we want to notify the users about.
important_only = models.BooleanField(
default=False,
help_text='Fire the event for important tasks only if checked.',
)
def should_be_fired(self, **kwargs) -> bool:
if self.important_only:
return Task.objects.filter(id=kwargs['task_id'], is_important=True).exists()
return True
# Then we need to fire `TaskCompletedEvent` when a task is marked as completed.
@receiver(Task.completed)
def on_task_completed(sender, task: Task, **kwargs):
for event in TaskCompletedEvent.objects.all():
transaction.on_commit(lambda: event.fire_single(task.user_id, task_id=task.id))
# At the end, create an Action implementing email notification.
class SendEmailAction(Action):
subject = models.CharField(max_length=256)
message = models.TextField()
def perform(self, user: User, context: Dict[str, Any]):
user.email_user(self.subject, self.message)
- Makemigrations and migrate
python manage.py makemigrations
python manage.py migrate
- Add trigger on the Django admin site
Don't forget to enable it :)
- Use the trigger!
task = Task.objects.get(id=...) # Get your task
task.complete() # And mark it as completed
You may also trigger it manually from the Django admin site if you're checking the test app example.
poetry run python -m django makemigrations --settings=tests.app.settings
poetry run isort triggers tests
poetry run flake8 triggers tests
poetry run mypy triggers tests
poetry run pytest