简体   繁体   中英

Django Admin sending email after post

So I'm familiar with sending emails using django, but I'd want to send an email to all those that subscribed to my newsletter if I were to use the admin panel instead of the one I have on the site itself. How would I go about doing this? For my current view on the user site version, it is something like:

    def form_valid(self, form):
        message = 'A new article has been released...'
        subject = 'New Article!'
        to = Email.objects.values_list('email', flat=True).distinct()
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, message, from_email, to, fail_silently=True)

        return super().form_valid(form)

Using django signals will do it via admin or via site doesnt matter.

You can create a signal in blog post view like this:

@receiver(post_save, sender=BlogPost)
def send_mail_to_subs(sender, instance, created, **kwargs):
    if created:
        for subs in instance.author.subscribed.all():
            send_mail(
                f'New Post from {instance.author}',
                f'Title: {instance.post_title}',
                'youremail',
                [subs.email],
            )

Good coding:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM