Search code examples
djangoemaildjango-modelsdjango-email

django sending mail using pre_save


1.As a part of learning django i am trying to send a mail to an email id using pre_save signal.

2.A mail should sent to an email id which is mentioned in the field.I dont't have a proper way to do using signals.Here i am giving the models.py and views.py.

views.py

def addbook():  


    form = BookForm

    if request.POST:
        form = BookForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            form.save()
            return redirect('/index/')
    return render_to_response('addbook.html',{ 'form':form },context_instance=RequestContext(request)) 

models.py

class Book(models.Model):

    book_id=models.AutoField(primary_key=True,unique=True)
    book_name=models.CharField(max_length=30)
    author_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    email = models.EmailField()
    bookref = models.CharField(max_length=10)
    class Meta:
        db_table = u'Book'

    def __unicode__(self):
        return "%d %s %s %s %s" % (self.book_id,self.book_name, self.author_name,self.publisher_name,self.email,self.bookref)

my requirement is an email should send automatically to the id in the field while submitting the book details.

An example about this to do will be great help.

Thanks


Solution

  • Under the Book models, create the signal function.

    class Book(models.Model):
        [..........]
    
    def send_update(sender, instance, created, **kwargs):
        if instance.author_name:
            message = "Book is updated"
            subject = "Updates"
            send_mail(subject, message, your_email,
                [instance.email,])
    
    post_save.connect(send_update, sender=Book)