Search code examples
pythondjangosignals

Getting False value even on creating a new User instace in Django signal receiver function, Why don't know?


This is my Signal Definition

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

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs): 
    user = instance
    if created: 
        print('A new user is created')
    else: 
        print('A new user is not created')
    
    print(sender, user, created)

I am using django-allauth package to authenticate user Currently i'm using the very simple account authenticating only

Here is the how i have registered signal in my a_users.apps.py:

    def ready(self): 
        print('Ready method is executing')
        import a_users.signals

Here is my projects settings.py file

"""
Django settings for a_core project.

Generated by 'django-admin startproject' using Django 5.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-ip6_#ne%exiu=@9a0rbb(_b%9b*oxe+ejyyfm0lmd4+f@v#r()'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]


# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'a_posts',
    # 'django.contrib.sites',
    'allauth',
    'allauth.account',
    'a_users',
    'django_cleanup.apps.CleanupConfig'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'allauth.account.middleware.AccountMiddleware',
]

AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by email
    'allauth.account.auth_backends.AuthenticationBackend',
]

ROOT_URLCONF = 'a_core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'a_core.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Media file configuration (User uploaded images or files)
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Where the media files to be stored


# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# Allauth Configuration
LOGIN_REDIRECT_URL = '/posts/'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True 

ACCOUNT_USERNAME_BLACKLIST = [
    'admin', 'student', 'profile', 
    'category', 'posts','accounts',
    'edit', 'delete',
]

I should get True ideally in the create_profile function whenever i create a new user But unfortunately i am not getting True rather every time i am getting False Value I can not understand why it is happening

In order to test whether this problem is persist with other Models I tried a post_save signal for Profile Model and it worked as expected without any issue.

Here is what I wrote for Profile signal

@receiver(post_save, sender=Profile)
def profile_created(sender, instance, created, **kwargs): 
    if created: 
        print("A new profile is created")
    else: 
        print("A new profile is not created")
        print("A new profile is updated")

    print(sender, instance, created)

One more strange thing is happening that when i am creating user through *CLI my signal is not even getting activated.

Thanks in Advance!!


Solution

  • You can start with this:
    from django.apps import AppConfig
    
    class YourAppConfig(AppConfig):
        name = 'your_app'
    
        def ready(self):
            import your_app.signal
    
    Next part more debug tool:
    
    @receiver(post_save, sender=User)
    def create_profile(sender, instance, created, **kwargs): 
        user = instance
        print("User pk:", user.pk)
        print("Created flag:", created)
        
        if created: 
            print('A new user is created')
        else: 
            print('A new user is not created')
        
        print(sender, user, created)
    
    Do you use bulk_create?