Question

I am using signals to send a mail and is working fine(right now I am testing it and providing the static email address). But I want to use Dynamic values of model fields in my mail function.

e.g. If admin changes anything from admin dashboard in that model a signal is called using post_save and a mail function is called so. But I need id of that user from this model so that I can fetch his name,email_address from auth_user table.

I am sending the name of the model in post_save but i don't know how to use their fields in signals if possible.

right now I am using this code.

My model

class ABC(models.Model):
  .....
  .......

post_save.connect(handlers.model_saved, sender=ABC)

the signal which is called.

from django.core.mail import send_mail


def model_saved(sender, **kwargs):
    send_mail('Subject here', 'Here is the message.', 'from@example.com',
    ['ndhiman08@gmail.com'], fail_silently=False)
    print "SAVED",sender,kwargs

Terminal response

<class 'XYZ.models.ABC'> {'raw': False, 'instance': <ABC: #1 admin admin 2013-01-04 04:20:50+00:00>, 'signal': <django.dispatch.dispatcher.Signal object at 0xb612584c>, 'using': 'default', 'created': False}

Please suggest me some way so that i can use vales of my model fields in signals.

Thanks.

Was it helpful?

Solution

There is instance argument provided to signal handler which is the Model object saved. So you can use it as :

def model_saved(sender, **kwargs):
    send_mail('Subject here', 'Here is the message.', 'from@example.com',
    ['ndhiman08@gmail.com'], fail_silently=False)
    abc_obj = kwargs['instance']
    #can use fields as 
    #abc_obj.somefield
    print "SAVED",sender,kwargs

post_save documentation explains this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top