Home > Software engineering >  Django How to update some specific fields data after input from another model using signals
Django How to update some specific fields data after input from another model using signals

Time:10-26

I have some problem with django signals. I wanna update PermohonanWP status model fields from 'PROSES' to 'SUCCESS' after I Input data to PenelitiPemindahanWP. (Suppose i have already input data to PermohonanWP model with status = 'PROSES')

here my model.py

class PermohonanWP(models.Model):
      npwp = models.CharField(max_length=15, null=False)
      nama = models.CharField(max_length=100, null=False)
      status = models.CharField(max_length=20, null=True)

class PenelitiPemindahanWP(models.Model):
      permohonan_pemindahan = models.ForeignKey(PermohonanWP, on_delete=models.CASCADE)
      nomor_lhp = models.IntegerField(null=True)
      nomor_st = models.CharField(max_length=50, null=True)

here my signals i input it in model.py

@receiver(post_save, sender=PenelitiPemindahanWP, dispatch_uid="update_permohonan_id")
def update_permohonan(sender, instance, **kwargs):
    pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan)
    pemohon.status = "SUCCESS"
    pemohon.save()

I wanna update the status field from PermohonanWP but whenever i submit saved button, it not saved and not update the fields.

CodePudding user response:

Correct this

pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan)

to

pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan.id)

OR

Even simply :

pemohon = instance.permohonan_pemindahan

CodePudding user response:

You need to import your signals in apps config ready method

apps.py

from django.apps import AppConfig

class <App_name>Config(AppConfig):
    name = '<app name>'

    def ready(self): 
        import <app name>.signals

and your signal should look like,

@receiver(post_save, sender=PenelitiPemindahanWP, dispatch_uid="update_permohonan_id")
def update_permohonan(sender, instance, **kwargs):
    pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan.id)
    pemohon.status = "SUCCESS"
    pemohon.save()

Hope it works.

  • Related