Skip to content

Instantly share code, notes, and snippets.

@kylefox
Last active July 1, 2021 12:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kylefox/177091bd8e4d88ac0cc19496064fd7d3 to your computer and use it in GitHub Desktop.
Save kylefox/177091bd8e4d88ac0cc19496064fd7d3 to your computer and use it in GitHub Desktop.
Connecting Django Signals using the AppConfig ready handler: https://docs.djangoproject.com/en/1.10/ref/applications/#django.apps.AppConfig.ready
default_app_config = 'cn.apps.users.config.UsersAppConfig'
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
name = 'cn.apps.users'
def ready(self):
import signals # noqa
from django.dispatch import receiver
from django.db.models.signals import post_save, pre_delete
from django.contrib.auth.models import User
from .models import UserProfile
@receiver(post_save, sender=User, dispatch_uid="users.create_user_profile")
def create_user_profile(**kwargs):
"""
Automatically create a UserProfile for any newly created User.
"""
user = kwargs.get('instance')
if not hasattr(user, 'profile'):
UserProfile.objects.create(user=user)
@receiver(pre_delete, sender=UserProfile,
dispatch_uid="profiles.delete_profile_image")
def delete_profile_image(**kwargs):
"""
Deletes the UserProfile.image file.
"""
kwargs.get('instance').image.delete(save=False)
@teewuane
Copy link

teewuane commented Nov 9, 2018

After upgrading to Django 2, I'm having trouble with this same method. In the ready method, when I try to import signals, I get "No module named 'Signals'". Any thoughts on this? This was working with Django 1.10.

My bad, I found the answer in the docs here

@cizario
Copy link

cizario commented Oct 13, 2019

As per the documentation, it's recommended to avoid using default_app_config in __init__.py and require cn.apps.users.config.UsersAppConfig in INSTALLED_APPS

New applications should avoid default_app_config. Instead they should require the dotted path to the appropriate AppConfig subclass to be configured explicitly in INSTALLED_APPS.

INSTALLED_APPS = [
   ...
    'cn.apps.users.config.UsersAppConfig',
   ...
]

@amdshrif
Copy link

thanks guys, this has solved my issue with signals in Django 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment