Chidananda Nayak
Chidananda Nayak

Reputation: 1201

How to use Django Signals?

I'm practicing Signals, I have two models

models.py

class National_ID_Card(models.Model):
    name = *************
    ID = *************
    address = *************
    state = *************
    nation = **********

    def __str__(self):
        return self.name



class Driving_Licence(models.Model):
    name = *************
    ID = *************
    vehicle_type = **********
    callahan   = ***********

    def __str__(self):
        return self.name

forms.py

class NationalIDForm(forms.ModelForm):
    class Meta:
        model = National_ID_Card
        fields = ('__all__')

class DrivingLicenceForm(forms.ModelForm):
    class Meta:
        model = Driving_Licence
        fields = ('__all__')

I want when i will be saving instance of National_ID_Card it would populate the name and ID field of Driving_Licence from also. I can do so with overriding method of save but how to do so in django signals? I tried many examples but cannt able to figure it out.

Upvotes: 0

Views: 123

Answers (1)

Tevin Joseph K O
Tevin Joseph K O

Reputation: 2654

You can do it in a couple of ways:

from django.db.models.signals import post_save

def your_signal_fuction(sender, instance, **kwargs):
    # Your code goes here

post_save.connect(your_signal_fuction, sender=National_ID_Card)

Using receiver decorator

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=National_ID_Card)
def your_signal_fuction(sender, instance, **kwargs):
    # Your code goes here

Upvotes: 2

Related Questions