Home > Mobile >  send email on model create - django
send email on model create - django

Time:03-26

I want to send an email automatically when I create an invoice. Is that possible? What I'm after. I have a invoice model and I put send_email code in it "def save(self):", I'm making perfex CRM invoice system, so I'm using the foregin key in invoice model to get a customer, but whenever I create new invoice it says "The invoices “INV-b066” was added successfully." but in invoice model it shows nothing like it's empty model I even tried to open invoice using index number and restarted the server and migrations stuff and it didn't worked but if I remove def save(self): function it works perfectly fine I'm trying to send an email automatically on model create

Customer model

class Customers(models.Model):
    Your_Name = models.CharField(max_length=220)
    Email_Address = models.EmailField(max_length=220)
    Profession = models.CharField(max_length=220)
    phone = PhoneNumberField(unique=True)
    No_of_Persons = models.IntegerField()
    Packages = models.CharField(choices=PAKAGES, max_length=100)
    Address = models.CharField(max_length=220)
    City = models.CharField(choices=CITIES, max_length=10)
    Time = models.CharField(choices=TIME, max_length=10)
    Date = models.DateTimeField()
    Message = models.TextField()

    def __str__(self):
        return f'{self.Your_Name}'

Invoice model

class Invoice(models.Model):
    Customer = models.ForeignKey(Customers, on_delete=models.CASCADE)
    Invoice_Number = models.CharField(default=inv_num, max_length=10)
    Recurring = models.CharField(choices=Recurrings, max_length=12)
    Invoice_date = models.DateField()
    Due_date = models.DateField()
    Packages = models.CharField(choices=PAKAGES, max_length=100)
    Package_name = models.CharField(max_length=50)
    Package_description = models.TextField()
    Package_Quantity = models.IntegerField()
    Package_Price = models.IntegerField()

    def __str__(self):
        return f'{self.Invoice_Number}'

    def save(self):
        send_mail(
            'Subject',
            'message.',
            '[email protected]',
            ['*****@gmail.com'],
            fail_silently=False,
        )

CodePudding user response:

You have to actually save the invoice like this:

def save(self):
    send_mail(
        'Subject',
        'message.',
        '[email protected]',
        ['*****@gmail.com'],
        fail_silently=False,
    )
    return super(Invoice, self).save()

Also as a part of suggestion it is better to send email as separate task or service, you can use django signals or celery for that.

  • Related