django-allauth
django-allauth copied to clipboard
Why signals work only in model.py
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,
This doesn't seem like the right forum for this issue, however here's an example how to setup a signal in an app:
- 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()
- Override the default AppConfig to look for additional files in your
myapp
directory. In this case, importmyapp.signals
myapp/apps.py
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'myapp'
def ready(self):
import myapp.signals
- Register your custom AppConfig
myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'
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.