'Create a save data using Django post_save() Signal
Here I want to create a heatmap when a Lead is created, it'll create an example api for the particular API. This is my lead model and another model for the api, here I want to add a new example api when a new api is been created.
Lead- Signals.py
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from .models import Lead
from heatmap.models import HeatMap
@receiver(post_save, sender=Lead)
def create_heatmap_for_lead(sender, created,instance, **kwargs):
print("signal is sent to heatmap")
print("-------------------------------")
# if created:
# HeatMap.objects.create(lead=instance)
Heatmap - models.py
class HeatMap(ModelMixin):
heatmap_type = models.ForeignKey(Lead, on_delete=models.CASCADE)
status = models.CharField(max_length=255)
comment = models.TextField(null=True, blank=True)
followUpDate = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return str(self.status)
Solution 1:[1]
Edited
You have to change the signal function, You try to get created
from kwargs
. created is already defined in the function parameter also same for instance
. See the code for a better understanding:
@receiver(post_save, sender=Lead)
def create_heatmap_for_lead(sender, instance, created, **kwargs):
if created:
HeatMap.objects.create(heatmap_type=instance)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |