How to add a function after a record inserted in database using django admin?
Asked Answered
T

3

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 .

Told answered 25/2, 2019 at 10:50 Comment(4)
docs.djangoproject.com/en/2.1/topics/signalsEskilstuna
I think this SO answer could help you : https://mcmap.net/q/723039/-calling-a-function-in-django-after-saving-a-modelGiant
@Y.Bernard This is the answer i wanted , but the question is where to put the answer code ? i mean in admin.py or models.py , ....Told
@Told models.pyOppilate
R
5

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

Rock answered 25/2, 2019 at 11:2 Comment(0)
O
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
Oppilate answered 25/2, 2019 at 10:59 Comment(0)
G
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+

Goodwill answered 25/2, 2019 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.