Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 251
Dzejkob Avatar asked Oct 12 '22 06:10

Dzejkob


2 Answers

Maybe you could use the M2M Changed Signal instead? This signal is sent when the M2M field is changed.

like image 151
Evan Porter Avatar answered Oct 20 '22 04:10

Evan Porter


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.

like image 31
shadfc Avatar answered Oct 20 '22 04:10

shadfc