Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - signals. Simple examples to start

I am new to Django and I'm not able to understand how to work with Django signals. Can anyone please explain "Django signals" with simple examples?

Thanks in advance.

like image 912
Wickkiey Avatar asked Jan 06 '15 17:01

Wickkiey


People also ask

How do you write signals in Django?

There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown.

How does signal work in Django?

Django includes a “signal dispatcher” which helps decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place.

Should I use signals Django?

Only use signals to avoid introducing circular dependencies. If you have two apps, and one app wants to trigger behaviour in an app it already knows about, don't use signals. The app should just import the function it needs and call it directly.

What is the use of Post_delete signal in Django?

Django Signals - post_delete()To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.


1 Answers

You can find very good content about django signals over Internet by doing very small research.

Here i will explain you very brief about Django signals.
What are Django signals?
Signals allow certain senders to notify a set of receivers that some action has taken place

Actions :

model's save() method is called.
django.db.models.signals.pre_save | post_save

model's delete() method is called.
django.db.models.signals.pre_delete | post_delete

ManyToManyField on a model is changed.
django.db.models.signals.m2m_changed

Django starts or finishes an HTTP request.
django.core.signals.request_started | request_finished

All signals are django.dispatch.Signal instances.

very basic example :

models.py

from django.db import models from django.db.models import signals  def create_customer(sender, instance, created, **kwargs):     print "Save is called"  class Customer(models.Model):     name = models.CharField(max_length=16)     description = models.CharField(max_length=32)  signals.post_save.connect(receiver=create_customer, sender=Customer) 

Shell

In [1]: obj = Customer(name='foo', description='foo in detail')  In [2]: obj.save() Save is called 
like image 145
Prashant Gaur Avatar answered Sep 23 '22 17:09

Prashant Gaur