~crocmagnon/blog

ref: f6d6d7b850df58a2f5ce8e8555f9b0328462224d blog/articles/management/commands/notify_commenters.py -rw-r--r-- 2.1 KiB
f6d6d7b8Gabriel Augendre Add task to notify commenters once their comment has been moderated. 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from collections import defaultdict

from django.conf import settings
from django.core.mail import mail_admins, send_mass_mail
from django.core.management import BaseCommand
from django.db.models import Q
from django.template import Context, Engine
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.translation import ngettext

from articles.models import Comment


class Command(BaseCommand):
    help = "Check for pending comments and send an email to the admin."

    def handle(self, *args, **options):
        to_notify = (
            Comment.objects.filter(
                Q(status=Comment.APPROVED) | Q(status=Comment.REJECTED),
                user_notified=False,
            )
            .exclude(email=None)
            .exclude(email="")
        )
        by_email = {}
        for comment in to_notify:
            if comment.email not in by_email:
                by_email[comment.email] = {"approved": [], "rejected": []}
            if comment.status == Comment.APPROVED:
                by_email[comment.email]["approved"].append(comment)
            elif comment.status == Comment.REJECTED:
                by_email[comment.email]["rejected"].append(comment)

        email_data = []
        for email, comments in by_email.items():
            approved = comments["approved"]
            rejected = comments["rejected"]
            subject = ngettext(
                "Your comment has been moderated.",
                "Your comments have been moderated.",
                len(approved) + len(rejected),
            )
            blog_title = settings.BLOG["title"]
            message = render_to_string(
                "articles/comments_notification_email.txt",
                {"approved": approved, "rejected": rejected, "blog_title": blog_title},
            ).replace("'", "'")
            from_email = settings.DEFAULT_FROM_EMAIL
            recipient_list = [email]
            email_data.append((subject, message, from_email, recipient_list))
        send_mass_mail(tuple(email_data))
        to_notify.update(user_notified=True)