简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM