Reputation: 92
I want to send an email to each follower after creating the item. But I don't know how to get this field from Models, and also I don't know how to send each follower to relate following.
models.py
class Book(models.Models):
title = models.CharField(max_length=255)
author = models.ForeignKey(
"users.CustomUser", on_delete=models.SET_NULL, null=True
)
# This is my try
#But it doesn't work
@hook(AFTER_CREATE)
def send_followers(self):
user = Followers.objects.all()
followers_email = CustomUser.objects.filter(
followers__follower__in=, followers__following=self.author.profile)
if CustomUser.objects.filter(
followers__follower__in=CustomUser.objects.only(
'followers__follower'),
followers__following=self.author.profile
).exists():
send_mail(
"Article published",
'%s' % (
followers_email
),
"[email protected]",
[self.author.email],
fail_silently=False,
)
else:
pass
class CustomUser(AbstractUser):
gender = models.ForeignKey(
"Gender", on_delete=models.CASCADE, blank=True, null=True
)
class Followers(models.Model):
follower = models.ForeignKey(
"users.CustomUser", on_delete=models.CASCADE, null=True, blank=True)
following = models.ForeignKey(
"Profile", on_delete=models.CASCADE, null=True, blank=True)
class Profile(models.Model):
slug = models.SlugField(unique=True)
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
Upvotes: 0
Views: 56
Reputation: 585
Your requirement can be fulfilled with signals. In Django, signals are used to perform certain actions based on some events. In your case, you want to send emails to all the followers of the author whenever a new book is created. Code that sends mails can be implemented in receivers. post_save signal will be triggered whenever a new row is created in the Book model. The corresponding signal will be received by the 'send_mail' receiver and will be executed.
signals.py
from django.dispatch import receiver
@reciever(post_save, sender="Book")
def send_mail(sender, instance, **kwargs):
# get the user model row of the author. Since author field is in M2One relationship with CustomUser, we can access the id of the user.
user_obj = instance.author
# ProFile model is in One2One relationship with CustomUser. Get the profile instance/row corresponding to the user_obj.
profile_obj = user_obj.profile
followers_list = Followers.objects.filter(following=profile_obj)
#followers_list will be having a list of all the followers to whom mail can be sent. You can retrieve the email of the followers present in followers_list.
apps.py
from django.apps import AppConfig
class AppNameConfig(AppConfig):
name = 'AppName'
def ready(self):
import signals over here
Upvotes: 1