Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 420
rayashi Avatar asked Nov 24 '14 14:11

rayashi


2 Answers

Otiginal 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().

like image 54
wolendranh Avatar answered Nov 04 '22 11:11

wolendranh


I dont know if the paste is wrong, but in that code your model is named Avaliacao and not Aval, The Model and the sender argument has to match

like image 3
krs Avatar answered Nov 04 '22 11:11

krs