I have a contact form that users can use to send complaints. However, I want a situation where the support team can indicate if a complaint is resolved or not and it will trigger an email when the status change to 'Resolved'. By default, the complaint is 'pending'. I am currently using a signal.
Please, can someone help me because it's not sending email when the status change to 'Resolves'. what am I not doing right?
This is what I did:
@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,
'[email protected]',
['[email protected]'],
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,
'[email protected]',
['[email protected]'],
fail_silently=False,
)
Model
class Contact(models.Model):
STATUS_CHOICE = (
("1", "Pending"),
("2", "Resolved"),
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=15)
email = models.EmailField(max_length=254)
subject = models.CharField(max_length=100)
status = models.CharField(choices=STATUS_CHOICE, default="Pending", max_length=50)
created = models.DateTimeField(auto_now_add=True)
body = models.TextField()
class Meta:
ordering = ["-created"]
verbose_name_plural = "Contacts"
def __str__(self):
return f"Message from: {self.name}"
CodePudding user response:
Try using post_save instead of pre_save. Post_save will trigger when the data has been committed with save(), So at that instance the status will have been set to resolved.
CodePudding user response:
The first value is saved in database, so you need to check with that value. Repace 'Resolved' with '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,
'[email protected]',
['[email protected]'],
fail_silently=False,
)