Follow these steps to create notifications for administrators:
- Create the signals.py file, with the following content:
# viral_videos/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.template.loader import render_to_string
from .models import ViralVideo
@receiver(post_save, sender=ViralVideo)
def inform_administrators(sender, **kwargs):
from django.core.mail import mail_admins
instance = kwargs["instance"]
created = kwargs["created"]
if created:
context = {
"title": instance.title,
"link": instance.get_url(),
}
plain_text_message = render_to_string(
'viral_videos/email/administrator/message.txt',
context)
html_message = render_to_string(
'viral_videos/email/administrator/message.html',
context)
subject = render_to_string(
'viral_videos/email/administrator/subject.txt',
context)
mail_admins(
subject=subject.strip(),
message=plain_text_message,
html_message=html_message,
fail_silently=True)
- Next, we will need a template for the plain text message—something like the following:
{# templates/viral_videos/email/administrator/message.txt #}
A new viral video called "{{ title }}" has been created.
You can preview it at {{ link }}.
- We will also need a template for the HTML message, as follows:
{# templates/viral_videos/email/administrator/message.html #}
<p>A new viral video called "{{ title }}" has been created.</p>
<p>You can <a href="{{ link }}">preview it here</a>.</p>
- Then, we will need a template for the email subject, as follows:
{# templates/viral_videos/email/administrator/subject.txt #}
New Viral Video Added
- Create the apps.py file, with the following content:
# viral_videos/apps.py from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class ViralVideosAppConfig(AppConfig): name = "viral_videos" verbose_name = _("Viral Videos") def ready(self): from .signals import inform_administrators
- Update the __init__.py file, with the following content:
# viral_videos/__init__.py default_app_config = "viral_videos.apps.ViralVideosAppConfig"
- Make sure that you have ADMINS set in the project settings, similar to the following:
# settings.py or config/base.py
ADMINS = (
("Admin User", "[email protected]"), )