Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django signals How to perform post_save method with multiple senders and multiple instances?

I have two models Profile and Company

models.py

class Profile(models.Model):
    user = models.OneToOneField(User)
    company = models.ForeignKey('company.Company', null=True)
    phone = models.CharField(max_length=10, blank=True)

@receiver(post_save, sender=User)
@receiver(post_save, sender=Company)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
        Profile.objects.create(company=instance)
    instance.profile.save()

As you can see Profile is an user_model extension. I have got that working when sending only one instance.

models.py

class Company(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=10, blank=True, unique=True)
    phone = models.CharField(max_length=10, blank=True)

Company is created successfully. I want to save the name field in the Company to The Profile when a company is created.

views.py

def form_valid(self, form):
    company = form.save(commit=False)
    user = self.request.user
    name=form.cleaned_data['name']
    phone=form.cleaned_data['phone']
    company.name = name
    company.phone = phone
    company.user = user
    company.save()
    Profile.refresh_from_db()
    Profile.company = name
    Profile.save()
    return super(CompanyCreateView, self).form_valid(form)
like image 970
Kishan M Avatar asked Oct 24 '25 19:10

Kishan M


1 Answers

According to your model architecture, following should be the code for the signal based approach.

@receiver(post_save, sender=User)
@receiver(post_save, sender=Company)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        if sender.__name__ == 'User':
            Profile.objects.create(user=instance)
        # Company
        else:
            profile = Profile.objects.get(user=instance.user)
            profile.company = instance
            profile.save()
like image 157
Saji Xavier Avatar answered Oct 26 '25 08:10

Saji Xavier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!