Alex
Alex

Reputation: 2402

Django - send email when object is created

Generally, in order to send an email when an object is created, I would override the save method:

def save(self, *args, **kwargs):
    send_email(context)
    return super().save(*args, **kwargs)

However, I now need the context to contain an attribute of the object that cannot be known until the object is saved, namely the url of a File object associated with the model object.

I am aware that this can be done with post_save signal, but the docs give the impression that this is best used when disparate models need access to such information. I get the impression that it's not good practice to use it in a single-model setup like this.

I've tried this:

    foo = super().save(*args, **kwargs)
    send_email(foo.document.url)
    return foo

But foo seems to be None.

Upvotes: 0

Views: 525

Answers (2)

p14z
p14z

Reputation: 1810

Daniel's answer is correct, but if you only want to send the email when the object is created, not if it's updated, you should also check if the instance has a pk assigned, for example:

def save(self, *args, **kwargs):
    created = self.pk is None
    super().save(*args, **kwargs)
    if created:
        send_email(context)

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

The save method doesn't return anything. But the item is self, you can use that after calling super.

super().save(*args, **kwargs)
send_email(self.document.url)

Upvotes: 1

Related Questions