Search code examples
djangodjango-signals

sending mail on post_save django


I want to send mail when I create entry in database, I'm using django post_save signal for that, but I'm failing in doing that, I'm not sure what I'm I missing here, is there a change that someone can help me understand what is happening. I'm using postmarker for the email configuration.

model.py

class Winner(BaseModel):
    name = models.CharField(max_length=225, blank=True, null=True)
    email = models.EmailField(unique=True, db_index=True)
    telephone = models.CharField(max_length=225, blank=True, null=True)
    postal_code = models.CharField(max_length=225, blank=True, null=True)
    reseller_code = models.CharField(max_length=225, blank=True, null=True)
    company_contact = models.CharField(max_length=225, blank=True, null=True)
    company_name = models.CharField(max_length=225, blank=True, null=True)
    company_telephone = models.CharField(max_length=225, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    EMAIL_FIELD = 'email'

    class Meta:
        verbose_name = 'winner'
        verbose_name_plural = 'winners'

    def get_email(self):
        """
        Return the indentifying email for this Winner
        """
        return getattr(self, self.EMAIL_FIELD)

    def __str__(self):
        return self.get_email()

signal.py

def send_winner_info(sender, instance, created, **kwargs):
    winner = instance
    if created:
        winner_dict = {
            "Name: ", winner.name,
            "Email: ", winner.email,
            "Telephone: ", winner.telephone,
            "Postal Code: ", winner.postal_code,
            "Reseller Contact: ", winner.reseller_contact,
            "Company Name: ", winner.company_name,
            "Company Telephone: ", winner.company_telephone,
        }
        message = render_to_string('mails/winner.html', winner_dict)
        subject = "Giveaway Winner Information"
        from_email = settings.DEFAULT_FROM_EMAIL
        recipients_list = settings.DEFAULT_RECIPIENT_LIST
        send_mail(subject, message, from_email, recipient_list=recipients_list)


post_save.connect(send_winner_info, sender=Winner)

Solution

  • Is your signal triggering? Have you registered them?

    In your apps.py, inside your app, add the following:

    from django.apps import AppConfig
    
    
    class YourAppConfig(AppConfig):
        name = 'your_app_name'
    
        def ready(self):
            import your_app_name.signal  # noqa
    

    import your_app_name.signal this line here must match your app name, and the filename where you have your signals