【问题标题】:Updating Notification model in django using signals使用信号更新 django 中的通知模型
【发布时间】:2020-04-12 10:22:00
【问题描述】:

我正在做一个图书库存项目。 我正在尝试在添加新书后立即向用户发送通知。

我已经建立了这个通知模型:

...
class Notification(models.Model):
    title =models.CharField(max_length =255)
    message =models.TextField()
    viewed =models.BooleanField(default =False)
    user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete =models.CASCADE,)

    def __str__(self):
        return self.title

我能够构建在控制台中打印“已添加图书”的 post_save 信号。虽然我在保存通知表中的值方面面临挑战 这是signals.py文件:

from django.db.models.signals import post_save
# from django.dispatch import receiver
from books.models import Book
from .models import Notification

# @receiver(post_save,sender =Book)
def book_add_notify(sender,**kwargs):
    print('Book is added')
    Notification.objects.create(user =kwargs.get('instance'),
    title ='Thanks for adding your book!',
    message='Your book has been successfully Added')

post_save.connect(book_add_notify,sender =Book)

这是我收到的错误消息:

ValueError 在 /books/new/ 无法分配“”:“Notification.user”必须是“CustomUser”实例。

我不确定如何处理这个 CustomUser 错误。 让我知道是否需要更多信息。

【问题讨论】:

    标签: python django django-models django-signals


    【解决方案1】:

    信号由 Book 对象发送,因此您的实例是 Book 对象。 您应该在 Notification.objects.create() 中传递一个 CustomUser 对象 获取 CustomUser 对象的位置取决于您的应用程序。看起来可能是个书作者。

    【讨论】:

      猜你喜欢
      • 2012-01-25
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 2020-08-03
      • 2020-08-13
      • 1970-01-01
      相关资源
      最近更新 更多