pythondjangostatus

How to check the status field in models django and send mail to the user?


I've developed a Django ticketing system where users can submit tickets, and each ticket has a status field indicating whether it's resolved or not (True for resolved). I want to implement functionality where, upon a ticket's status changing to True, an email is sent to the user who posted the ticket.

Here's my tickets model:

from django.db import models
from django.contrib.auth.models import User

class Ticket(models.Model):
    name = models.ForeignKey(Device, on_delete=models.CASCADE, blank=True, null=True)
    location = models.CharField(max_length=200)       
    company = models.CharField(max_length=200)
    serial_number = models.CharField(max_length=200)
    problem = models.CharField(max_length=1000)
    contact_number = models.CharField(max_length=200)
    status = models.BooleanField(default=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tickets", null=True)
    executive = models.ForeignKey(Executive, on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return self.problem

How can I implement the feature to send an email to the user when the status of their ticket changes to True?


Solution

  • you can do like this

    from django.core.mail import send_mail
    
    class tickets(models.Model):
       email_as_send = models.BooleanField(default=False)
        ...
    
       def save(self):
           if self.status and self.email_as_send:
              send_mail("subject", "message","your_website@email.fr", [self.author.email])
              self.email_as_send = True
           super().save()