簡體   English   中英

為什么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>

編輯2:在此處添加default.jpg 在此處輸入圖片說明

如果您沒有附加profile的用戶,就會發生src(unknown) 這很可能意味着您的信號沒有被觸發,這是因為它們沒有被加載,這是因為您的UsersConfig應用程序沒有被首先加載。

有兩種加載應用程序的方式。 合適的是:

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

另一種方法是在yourapp/__init__.py設置default_app_config = 'yourapp.apps.UsersConfig' 請注意,我們不再建議將其用於新應用。

之后,您可能還需要修改signals.py如果嘗試保存未附加Profile Users ,則會觸發異常。

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

Profile Model中添加保存方法:

首先從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)

此處圖像尺寸減小。 如果需要,可以使用其他方式,而無需減小尺寸即可直接保存圖像。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM