Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I send for new model object create in django

I want to send email if user does something and because of his action some entry is made in the db. I want to do the send email function from my models.py. Is it possible??

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yes, there are many ways you can send your mail when some action is performed in the database. You can use Django’s signals post_save feature. Using signals, you can send emails to your user without any other editing in your code/view.

from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.core.mail import EmailMessage
@receiver(pre_save, sender=MyModel) # here MyModel is name of your model
def send_email(sender, instance, **kwargs):
   email = EmailMessage('your title', 'body', to=[email])
   email.send()

    # your code to send email
    ...

You also have to have your email setting in your settings.py file. I’m giving those here also.

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'Your email id'
EMAIL_HOST_PASSWORD = 'your password'
EMAIL_PORT = 587
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading