Django中使用django-allauth创建用户时,post_save信号的created参数始终为False且CLI创建用户时信号不触发的问题
Django中使用django-allauth创建用户时,post_save信号的created参数始终为False且CLI创建用户时信号不触发的问题
我的信号定义
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)
信号注册方式
我在a_users.apps.py中注册信号,代码如下:
def ready(self): print('Ready method is executing') import a_users.signals
项目settings.py配置
""" 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', ]
遇到的问题
我原本期望在创建新用户时,create_profile函数中的created参数会返回True,但实际每次都是False,我搞不懂为什么会这样。
为了排查问题,我给Profile模型也写了一个post_save信号测试,结果完全正常,符合预期:
@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)
还有个奇怪的现象:当我通过CLI创建用户时,这个User的post_save信号根本不会触发。
提前感谢大家的帮助!
备注:内容来源于stack exchange,提问作者big_0
相关产品推荐
相关产品推荐

