尽管一切就绪,Django仍然无法正常工作

问题描述 投票:0回答:1

我的案子在我的情况下,User是默认的django用户模型,我创建了一个Profile,以向User模型添加更多详细信息。实现现在我想要的是,每当我创建一个新用户时,都应该自动创建该用户的配置文件。我已经完成1.我已经检查了signals.py文件,也将信号导入了apps.py文件,但是仍然没有为正在创建的每个新用户创建nw配置文件:(2.尝试将“ users.apps.UsersConfig”添加到我的INSTALLED_APPS中,但效果也不理想。下面的代码我在下面的signal.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',
]
python django django-signals
1个回答
0
投票

我在INSTALLED_APPS中使用的是'users',而不是'users.apps.UsersConfig'。我的新工作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.apps.UsersConfig', #Signals wont work if you just write 'users'
]

或者只是参考一个类似的问题:https://stackoverflow.com/a/59028716/11687381

© www.soinside.com 2019 - 2024. All rights reserved.