为什么 post_save 信号在这里不起作用?

Why post_save signal is not working here?

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

@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>

edit-2: 这里添加了default.jpg

Profile里面添加保存方法 型号:

首先从PIL导入图片

from PIL import Image

那么您的个人资料模型如下:

    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)

       def save(self, *args, **kwargs):
          super().save()

           img = Image.open(self.image.path)

           if img.height > 300 or img.width > 300:
               output_size = (300, 300)
               img.thumbnail(output_size)
               img.save(self.image.path)

这里图片尺寸缩小了。如果你需要你可以使用否则你可以直接保存图像而不减小尺寸。

如果您没有 profile 附加到您的用户,就会发生

src(unknown)。这很可能意味着你的信号没有被触发,这是因为它们没有被加载,这是因为你的 UsersConfig 应用程序没有首先加载。

有两种加载应用程序的方法。 Proper one 将是:

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

另一种方法是在yourapp/__init__.py中设置default_app_config = 'yourapp.apps.UsersConfig'。请注意,对于新应用,它不再是 not recommended

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

@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)