0

I'm working on a books inventory project. I'm trying to send notification to user as soon as a new book is added.

I've built this notification model:

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

I'm able to build post_save signal that prints the 'Book is added' in the console. Though I'm facing challenge in saving the value in the notifications table This is the signals.py file:

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)

This is the error message I'm getting:

ValueError at /books/new/ Cannot assign "": "Notification.user" must be a "CustomUser" instance.

I'm not sure how to handle this CustomUser error. Let me know if any more info is required.

jitesh2796
  • 164
  • 6
  • 14

1 Answers1

1

The signal is sent by a Book object, so your instance is a Book object. You should be passing a CustomUser object in Notification.objects.create() Where you gonna get the CustomUser object depends on your application. Might be a book author by the looks of it.