Home > Software design >  Django Signals not triggering when only using apps.py
Django Signals not triggering when only using apps.py

Time:12-16

Here I want to create a Datalog when a new Customer create an account. I want to trigger the Datalog event and save the relevant information into the Datalog table.

(I could write in signals.py but I prefer to write it into directly app.py)

apps.py

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .models import DataLog

class LogAPIconfig(AppConfig):
     default_auto_field = 'django.db.models.BigAutoField'
     name = 'myapp'

     def ready(self):
        @receiver(post_save, sender=DataLog)
        def log_save_actioner(sender, created,instance, **kwargs):
            print("signal is sent to heatmap")
            action = 'create' if created else 'update'
            Datalog.objects.create(
                heatmap_type = instance.heatmap_type,
                status = instance.status,
                action = action,
                sender_table = sender.__name__,
                timestamp = instance.timestamp
            )

models.py

class Customer(models.Model):
        Customer_name = models.ForeignKey(User, unique=True, primary_key=True, related_name="Customer_name")
        Customer_type = models.CharField(max_length=255)

class Datalog(models.Model):
    Customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE)
    status = models.CharField(max_length=255)
    comment = models.TextField(null=True, blank=True)
    followUpDate = models.DateTimeField(auto_now_add=True)
    class Meta:
        ordering = ['-followUpDate']

    def __str__(self):
        return str(self.status)

settings.py

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "rest_framework.authtoken",
    "corsheaders",
    "django_auth_adfs",
    "django_filters",
    'myapp.apps.LogAPIconfig',

]

When I implemented this I got following error message in the terminal

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

after some search I think this is somewhat related with importing Datalog table. I want to know

  • Is this something related because of I'm not using signals.py directly ?
  • Who should be the sender?
  • Do I need to use post_save.connect(log_save_actioner, sender=User) ?

CodePudding user response:

You are importing your model too early for Django to handle it correctly. Try moving 'from .models import DataLog' to inside your ready(self) function.

  • Related