Search code examples
pythondjangodjango-signals

Django signals doesn't work


My models.py:>

class Aval(models.Model):
    cliente = models.ForeignKey(Cliente)
    salao = models.ForeignKey(Salao)
    rate = models.IntegerField(choices=RATE, default=5)
    criacao = models.DateTimeField(blank=True, null=True, auto_now=True)
    comentario = models.TextField(max_length=400, blank=True, null=True, default=None)
    aprovado = models.BooleanField(default=False)

My signals.py:>

@receiver(post_save, sender=Aval)
def new_rate(sender, instance, created, **kwargs):
    aval = instance

    print("Aval is saved.")

I'm testing the signal post_save for Aval model, When I'm save some object Aval it not printing "Aval is saved" . What I'm doing wrong ?


Solution

  • Original answer for Django < 1.7:

    You should include:

    import signals
    

    to __init__.py file of your application.

    Edit: Django >= 1.7:

    Signals can be registered in django.apps.AppConfig.ready as described in Signals documentation and AppConfig doc

    Where should this code live?

    Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code.

    In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, import the signals submodule inside ready().