6

I want to execute a function after a record inserted to database using django-admin panel .

I have a product table , i want to send notification to users when a record inserted in database by django admin panel . i know how to send notification to users , but i dont know where to put my code .

any suggestion will be helpfull .

How can i execute a function to notify user after my record inserted ?

here is my code to execute after record inserted :

from fcm_django.models import FCMDevice

device = FCMDevice.objects.all()

device.send_message(title="Title", body="Message", icon=..., data={"test": "test"})

i searched alot but not found anything usefull .

thanks to this great communtiy .

T.Pool
  • 145
  • 1
  • 2
  • 13

3 Answers3

4

You can modify save method on your product model

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    device = FCMDevice.objects.all()
    device.send_message(title="Title", body="Message", icon=..., data={"test": "test"})

Well, it will send the notification every time the instance is saved (not only when it was added in django admin panel).

marke
  • 1,024
  • 7
  • 20
2

You need to use the Django model post_save signals to achieve this. This signal receiver can be placed in the same place where the model is

class FCMDevice(models.Model):
    ...

@receiver(post_save, sender=FCMDevice)
def notify_users(sender, instance, **kwargs):
     # your logic goes here
     # instance is referred to currently inserted row
     pass
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Muthu Kumar
  • 885
  • 2
  • 14
  • 25
0

You might wanna check post_save signal. From the docs:

Like pre_save, but sent at the end of the save() method.

url: https://docs.djangoproject.com/en/2.1/ref/signals/#post-save

django-version: 1.7+

Lex Bryan
  • 750
  • 1
  • 9
  • 18