Using Django's signals
In Django, we can use signals to decouple application logic and perform tasks when certain events occur. Signals allow us to define sender/receiver relationships and execute code when a signal is sent. Here's an example signal that sends an email when a new blog post is created:
python
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
from .models import Post
@receiver(post_save, sender=Post)
def send_new_post_notification(sender, instance, **kwargs):
subject = f'New blog post: {instance.title}'
message = f'A new blog post was created with the title "{instance.title}".'
recipient_list = ['admin@example.com']
send_mail(subject, message, 'admin@example.com', recipient_list)
In this example, we define a send_new_post_notification receiver function that sends an email when a Post object is saved. We use the post_save signal and specify the sender as the Post model. We define the subject, message, and recipient_list variables for the email and use Django's send_mail function to send the email.
We can connect our receiver function to the signal by importing it in our app's apps.py file and connecting it in the ready method:
python
from django.apps import AppConfig
class MyAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapp'
def ready(self):
import myapp.signals
In this example, we import our signal receiver function and connect it to the signal in the ready method of our app configuration class.
No comments:
Post a Comment