Question

In my sample, signal function was created in models.py.Instead of this,i think it is possible to do using custom signals concept.

my models.py for signals function is

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)

views.py is

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))

Instead of this how can we create a custom signals using signals.py file to send the mail.

I am trying to learn this in practical,an example will help me to do that.

Thanks

Was it helpful?

Solution

signals.py

from django.db.models.signals import post_save
from app.models import Book

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)

Register the signals by importing it in the app's __init__.py file. This will allow to import models from signals.py.

__init__.py

import signals

OTHER TIPS

Define your signal and receiver in signals.py:

from django.dispatch import Signal

post_update = Signal(providing_args = ['instance'])

def send_update(...):
    ....

post_update.connect(send_update, sender = Book)

In views.py, send the signal right after you save the form:

instance = form.save()
post_update.send(sender = Book, instance = instance)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top