django-allauth icon indicating copy to clipboard operation
django-allauth copied to clipboard

Why signals work only in model.py

Open cyrilmarceau opened this issue 2 years ago • 1 comments

Hi,

I search to create a file signals.py but if my signal is not in models.py it's not working. DO you know why ? It's possible to do this in separate file ?

Tout le monde explique que sa marche seulement dans le fichier models.py mais il n'y a pas d'explication

Thanks,

cyrilmarceau avatar May 05 '22 23:05 cyrilmarceau

This doesn't seem like the right forum for this issue, however here's an example how to setup a signal in an app:

  1. Create the signal

myapp/signals.py

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import MyModel

@receiver(post_save, sender=User)
def create_user(sender, instance, created, **kwargs):
    ''' Creates an instance of MyModel when a user is created.
    '''
    if created:
        my_model = MyModel .objects.create(user=instance)
        my_model.save()
  1. Override the default AppConfig to look for additional files in your myapp directory. In this case, import myapp.signals

myapp/apps.py

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'
    def ready(self):
        import myapp.signals
  1. Register your custom AppConfig

myapp/__init__.py

default_app_config = 'myapp.apps.MyAppConfig'

jharmon96 avatar Jun 08 '22 01:06 jharmon96

This is not an issue in allauth. You need to hookup signals in code that runs when Django boots -- I would recommend the ready approach.

pennersr avatar Dec 10 '22 21:12 pennersr