Search code examples
djangodjango-modelsdjango-signals

Access to related data of newly created model instance using post_save signal handler


I need to send an e-mail when new instance of Entry model is created via admin panel. So in models.py I have:

class Entry(models.Model):   
    attachments = models.ManyToManyField(to=Attachment, blank=True)
    #some other fields
    #...
    sent = models.BooleanField(editable=False, default=False)

Then I'm registring post_save handler function:

def send_message(sender, instance, **kwargs):
    if not instance.sent:
        #sending an e-mail message containing details about related attachments
        #...
        instance.sent = True
        instance.save()

post_save.connect(send_message, sender=Entry)  

It works, but as I mentioned before, I also need to access related attachments to include their details in the message. Unfortunatelly instance.attachments.all() returns empty list inside send_message function even if attachments were actually added.

As I figured out, when the post_save signal is sent, related data of saved model isn't saved yet, so I can't get related attachments from that place. Question is: am I able to accomplish this using signals, or in any other way, or do I have to put this email sending code outside, for example overriding admin panel change view for Entry model?


Solution

  • You should be able to do this by overriding the save_model() method on the ModelAdmin. You could either send your email in there or fire a custom signal which triggers your handler to send the email.

    If you have inlines, I believe you need to use save_formset() instead.