Я новичок в коде.
У меня есть этот код, который генерирует уведомления каждый раз, когда выполняется действие, связанное с данным пользователем.
На данный момент уведомления генерируются и сохраняются в таблице.
Я хочу также отправить уведомления связанному пользователю.
Это сигнал, который отправляет электронное письмо при создании уведомления:
def email_notification(sender, instance, created, **kwargs):
""" sends an email notification for notifications """
user = instance.recipient
recipients = User.objects.filter(email=user)
deactivation_link = "link.com"
if created:
for recipient in recipients:
if recipient.email_notification is True:
mail_helper.send_mail(
subject="Author's Haven notifictions",
to_addrs=recipient.email,
multiple_alternatives=True,
template_name='notifications.html',
template_values={
'username': recipient.username,
'optout_link': deactivation_link,
'description': instance.description
}
)
post_save.connect(email_notification, sender=Notification)
Метод отправки электронного письма, который я использую, таков:
def send_mail(self, subject, message=None,
to_addrs=[], multiple_alternatives=False, template_name=None,
template_values={}):
"""
Sends an email using the specified addresses
Parameters:
----------
subject: str
Email subject
to_addrs: list
Email receipients
message: str
Email body (for a plain/text email format)
multiple_alternatives: boolean
Send email in text/html format
If false, email is sent as plain text
template_name: str
The path to the HTML template to send email in
Requires multiple alternatives set to True
template_values: dict
key: pair items to render in the template message
"""
if multiple_alternatives:
template = render_to_string(template_name, template_values)
body_msg = strip_tags(template)
email = EmailMultiAlternatives(
subject, body_msg, self.sender_email, to_addrs)
email.attach_alternative(template, 'text/html')
email.send()
elif not multiple_alternatives:
_send_mail(subject, message, to_addrs)
Это мой шаблон электронной почты:
{% extends 'authors/apps/authentication/templates/emailing_template.html' %}
{% block body %}
Here
<div id="email-verification">
<p id="greeting">Hey <span id="name">{{ username }}</span>,</p>
<p id="text-body"><span id="shout">Yaaay!</span> You are now on Authors' Haven.</p>
<p> Click on the button below to activate your account: </p>
<div id="activation-button">
<p>{{ description }}</p>
</div>
<div class="failed-button">
<p>If the button doesn't work, copy the link below and paste it in your browser:
{{ activation_link }}</p>
</div>
</div>
{% endblock %}
Наконец, вот моя структура папок:
authors/apps/notifications/
├── __init__.py
├── models.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── renderers.cpython-36.pyc
│ ├── serializers.cpython-36.pyc
│ ├── signals.cpython-36.pyc
│ ├── urls.cpython-36.pyc
│ └── views.cpython-36.pyc
├── renderers.py
├── serializers.py
├── signals.py
├── templates
│ ├── __init__.py
│ └── notifications.html
├── tests
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-36.pyc
│ │ └── test_notifications.cpython-36-PYTEST.pyc
│ └── test_notifications.py
├── urls.py
└── views.py
Создает уведомления, но не отправляет их на электронную почту пользователя. Возникает ошибка:
TemplateDoesNotExist at /api/articles/
authors/apps/authentication/templates/emailing_template.html
Как мне заставить django отправить электронное письмо с шаблоном?