Home > Blockchain >  How to Add data when a create django post_save() signal
How to Add data when a create django post_save() signal

Time:05-03

This is my lead model and another model for the heatmap, here I want to add a new heatmap when a new lead is been created.

Lead models.py

class Lead(ModelMixin):
lead_type = models.CharField(max_length=128)
lead_status = models.CharField(max_length=128)
agent_applied = models.UUIDField()
co_broke_agent = models.UUIDField(null=True, blank=True)
sell_within_three_years = models.BooleanField(default=False)
has_200k_down = models.BooleanField(default=False)
loan_category = models.CharField(max_length=128, null=True)
loan_amount = models.FloatField(null=True)
outstanding_loan_amount = models.FloatField(null=True)
existing_bank = models.ForeignKey(Bank, related_name="leads", on_delete=models.PROTECT, null=True)
current_interest_rate = models.FloatField(null=True, blank=True)

# Add law firm here last stage.

class Meta:
    ordering = ['-created']

def __str__(self):
    return self.lead_type

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, instance, created, **kwargs):
if kwargs['created']:
    heatmap = HeatMap.objects.create(client=kwargs['instance'])

Heatmap - models.py

class HeatMap(ModelMixin):


heatmap = models.CharField(max_length=255, choices=HEAT_MAP)
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)

Heatmap- models.py

CodePudding user response:

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 = HeatMap.objects.create(client=instance)

But I was surprised that there is no field called client in the HeatMap model.

  • Related