【发布时间】:2020-06-26 22:00:57
【问题描述】:
我的情况
在我的例子中,用户是默认的 django 用户模型,我创建了一个配置文件以向用户模型添加更多详细信息。
实现
现在我想要的是,每当我创建一个新用户时,应该自动为该用户创建一个配置文件。
我已经完成了
1. 我检查了我的 signals.py 文件,并将信号导入到了 apps.py 文件中,但仍然没有为每个正在创建的新用户创建 nw 配置文件:(
2. 尝试将“users.apps.UsersConfig”添加到我的 INSTALLED_APPS,但效果不佳。
以下代码
我在下面的 signals.py 和 apps.py 文件中提供了代码。
请问我是否需要更多代码
并提前感谢:)
这是我的 signals.py 文件
#This is the signal that will be sent
from django.db.models.signals import post_save
#This is the object which will send the signal
from django.contrib.auth.models import User
#This will receive the signal
from django.dispatch import receiver
#We need this to perform operations on profiles table
from .models import Profile
#This function creates new profile for each user created
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#This function saves those newly created profiles
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
这是我的 apps.py 文件
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
这是我的 INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#Custom Apps
'product',
'shop',
'market',
'pages',
'users',
]
【问题讨论】:
-
你的
users.apps.UsersConfig是INSTALLED_APPS吗? -
顺便说一句,自定义用户模型是一种更现代且不易出错的自定义配置文件方式。
-
@AKX 不,它没有放在那里,我已经在我的 INSTALLED_APPS 中放置了“users.apps.UsersConfig”,现在它在重新启动服务器时给了我这个错误:“django.core.exceptions .ImproperlyConfigured:应用程序标签不是唯一的,重复:用户”
-
-
@AKX 是的,你是对的,谢谢 :)
标签: python django django-signals