0

I want to send out an email when a model instance is saved. To do this I listen out for the post_save signal:

#models.py
@receiver(post_save, sender=MyModel, dispatch_uid="something")
def send_email(sender, **kwargs):
    instance = kwargs['instance']
    email = ModelsEmailMessage(instance)  
    email.send()

In my view I process the form and append subscribers to the object:

#views.py
object = form.save()
object.subscribers.add(*users)

My problem is that the form save triggers the post_save signal before the users have been added.

But if I do this:

object = form.save(commit=False)

then I can't add m2m instances to an object that has no id.

Heyulp!

powlo
  • 2,538
  • 3
  • 28
  • 38
  • so `subscribers` is a m2m field, right? and you can't just do the email sending in the model's `save()` method? – scytale Jul 24 '12 at 11:30
  • https://docs.djangoproject.com/en/1.4/ref/signals/#m2m-changed – rantanplan Jul 24 '12 at 11:48
  • @scytale: No you can't do the sending in the models save() because the m2m references do not yet exist. There will be no subscribers so no email will be sent. – powlo Jul 24 '12 at 14:58
  • @rantanplan: m2m_changed doesn't do it as far as I can tell, because I don't want to mail people if someone subscribes, or unsubscribes. I want to mail when the content changes. If i understand the signal correctly, if someone makes a change and the m2m doesn't change then the signal won't be sent. – powlo Jul 24 '12 at 15:01
  • Yes, thats why I upvoted Rohan. You have to make a custom signal. – rantanplan Jul 24 '12 at 15:15

1 Answers1

2

Most likely you will have to write your own signal to send email.

Event though you are implemented that tries to send email when object is saved, but that is not what you want. You want to send email when object is saved and has some subscribers added after processing some view. i.e. its 2 step operation.

Rohan
  • 52,392
  • 12
  • 90
  • 87
  • +1 Rohan is correct. OP definitely needs a custom signal, because only he knows when the subscribers list is ready. – rantanplan Jul 24 '12 at 11:53