Skip to content

Instantly share code, notes, and snippets.

@melianmiko
Last active January 7, 2023 11:00
Show Gist options
  • Save melianmiko/01155bc1435e6d47f53a4a23bdac77f7 to your computer and use it in GitHub Desktop.
Save melianmiko/01155bc1435e6d47f53a4a23bdac77f7 to your computer and use it in GitHub Desktop.
Django Comments XTD EMail notifications
from django.core.mail import send_mail
from django.db import models
from django.dispatch import receiver
from django_comments_xtd.models import XtdComment
class CommentMailFilter(models.Model):
# To prevent duplicate mails
id = models.IntegerField(primary_key=True)
def _comment2html(comment: XtdComment, with_header=True):
response = ""
if with_header:
url = comment.get_content_object_url()
response += f"<a href='{url}'>View page</a><hr/>"
response += f"<p><b>{comment.user or comment.name}</b> wrote:</p>"
response += f"<blockquote>{comment.comment}</blockquote>"
if comment.parent_id != comment.id:
parent = XtdComment.objects.get(id=comment.parent_id)
response += f"<p>at {comment.submit_date}, reply to:</p>"
response += _comment2html(parent, with_header=False)
else:
response += f"<p>at {comment.submit_date}</p>"
return response
@receiver(models.signals.post_save)
def comment_to_email(instance: XtdComment, **kwargs):
if not isinstance(instance, XtdComment):
return
if not instance.is_public or instance.is_removed:
return # Don't send hidden comments
if instance.user and instance.user.groups.filter(name="Editors").exists():
return # Don't send editor's comments
if CommentMailFilter.objects.filter(id=instance.id).exists():
return
# Prevent duplicate mail send
CommentMailFilter(id=instance.id).save()
user_name = instance.user or instance.name
send_mail(f"{user_name} commented on {instance.site.domain}",
instance.get_as_text(),
"comments@melianmiko.ru",
["admin@melianmiko.ru"],
html_message=_comment2html(instance),
fail_silently=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment