Search code examples
djangodjango-signals

Django Singal Populating one model if another model is populated


I have a Django project with two apps.. one is contact and annother is contactus

my contact model is: project/contact/models.py below:

from django.db import models

class ContactList(models.Model):
    phone = models.CharField(max_length=15)
    email = models.EmailField()

and my contactus model is: project/contactus/models.py below:

from django.db import models

class ContactUs(models.Model):
    subject = models.CharField(max_length=50)
    phone = models.CharField(max_length=15)
    email = models.EmailField()
    message = models.TextField()

I want when ContactUs class gets data by user input, in the same time, ContactUs's phone and email should be populated in ContactList class

I created two signal.py file in my two apps but tried a lost with some code, i failed.. i think this is the very easiest task for expert.. Can anyone help me to solve this problem?


Solution

  • Since you want to do something when data is saved in ContactUs you should use the post_save signal like this:

    @receiver(post_save, sender=ContactUs)
    def add_to_list(sender, instance, created, **kwargs):
        if created:
            ContactList.objects.create(phone=instance.phone, email=instance.email
    

    This signal will create a ContactList object when a ContactUs object is created and assigns the phone and email values of the ContactUs instance to the phone and email fields of the ContactList object.

    More information about Django signals can be found in the docs