Как вызвать электронное письмо при изменении поля
У меня есть контактная форма, которую пользователи могут использовать для отправки жалоб. Однако я хочу, чтобы служба поддержки могла указать, решена ли жалоба или нет, и чтобы при изменении статуса на "Решена" отправлялось электронное письмо. По умолчанию жалоба находится в состоянии "на рассмотрении". В настоящее время я использую сигнал
Пожалуйста, кто-нибудь может мне помочь, потому что он не отправляет электронную почту, когда статус меняется на 'Resolves'. что я делаю неправильно?
Вот что я сделал:
@receiver(pre_save, sender=Contact)
def send_email_on_status_change(sender, instance, **kwargs):
# Check if the field that you want to watch has changed
if instance.status == 'Resolved':
# Construct and send the email
subject = "Contact status changed"
message = "the status of this complaint has changed to has changed to '{}'".format(instance)
send_mail(
subject,
message,
'sender@example.com',
['recipient@example.com'],
fail_silently=False,
)
@receiver(pre_save, sender=Contact)
def save_status(sender, instance, **kwargs):
instance.status.save()@receiver(pre_save, sender=Contact)
def send_email_on_status_change(sender, instance, **kwargs):
# Check if the field that you want to watch has changed
if instance.status == 'Resolved':
# Construct and send the email
subject = "Contact status changed"
message = "the status of this complaint has changed to has changed to '{}'".format(instance)
send_mail(
subject,
message,
'sender@example.com',
['recipient@example.com'],
fail_silently=False,
)
Попробуйте использовать post_save вместо pre_save. Post_save сработает, когда данные будут зафиксированы с помощью save(), поэтому в этом случае статус будет установлен на resolved.
Первое значение сохраняется в базе данных, поэтому проверку нужно проводить с этим значением. Замените 'Resolved' на '2'
@receiver(post_save, sender=Contact)
def send_email_on_status_change(sender, instance, **kwargs):
# Check if the field that you want to watch has changed
if instance.status == '2':
# Construct and send the email
subject = "Contact status changed"
message = "the status of this complaint has changed to has changed to '{}'".format(instance)
send_mail(
subject,
message,
'sender@example.com',
['recipient@example.com'],
fail_silently=False,
)