首页 > 解决方案 > 为什么 post_save 信号在这里不起作用?

问题描述

我创建了一个在创建用户时创建配置文件的信号。以前,相同的代码在其他项目中运行良好。在这里,我不知道我做错了什么,它不起作用并且没有为创建的用户创建配置文件。这就是信号。

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    print(instance)
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

所有导入都正确完成,在这里我将其导入到我的应用程序中:

class UsersConfig(AppConfig):
    name = 'users'

    def ready(self):
        import users.signals

如果您想查看配置文件模型:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return "{} Profile".format(self.user.username)

由于我创建了一个信号,因此对于所有新创建的用户,它应该将其添加default.jpg为默认个人资料图片。

但是,如果我创建一个新用户,登录然后转到个人资料页面,它会显示如下内容:

在此处输入图像描述

如果我去管理员并手动添加此个人资料图片,它就可以正常工作。最后一件事我还添加了以下设置urls.py

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

请帮我修复它,我尝试了所有可能的方法已经 3 小时,但无法使其正常工作。谢谢您的帮助。

编辑: template

<div class="media">
    <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
    <div class="media-body">
        <h2 class="account-heading">{{ user.username }}</h2>
        <p class="text-secondary">{{ user.email }}</p>
    </div>
</div>

编辑2:default.jpg在这里添加! 在此处输入图像描述

标签: pythondjangosignals

解决方案


src(unknown)如果您没有profile附加到您的用户,就会发生这种情况。这很可能意味着您的信号没有被触发,这是因为它们没有被加载,这是因为您的UsersConfig应用程序没有被首先加载。

有两种加载应用程序的方式。适当的将是:

INSTALLED_APPS = [
# ...
'yourapp.apps.UsersConfig'
]

另一种方法是设置default_app_config = 'yourapp.apps.UsersConfig'yourapp/__init__.py. 请注意,不再推荐用于新应用程序。

之后,您可能还想修改signals.py- 如果您尝试保存UsersProfile附加的内容,则会触发异常。

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    if hasattr(instance, 'profile'):
        instance.profile.save()
    else:
        Profile.objects.create(user=instance)

推荐阅读