4

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)
Kishan M
  • 173
  • 2
  • 13
  • Possible duplicate of [Consolidating multiple post\_save signals with one receiver](https://stackoverflow.com/questions/17507784/consolidating-multiple-post-save-signals-with-one-receiver) – Clément Denoix Nov 22 '17 at 06:21
  • I have seen that before. I get that and how multiple senders can be used in a signal. I want to know how to pass multiple instances in a single signal. `views.py` would give a better understanding. – Kishan M Nov 22 '17 at 06:27
  • Django built-in signals cannot handle this case. You should built your own signal instead: https://docs.djangoproject.com/en/1.11/topics/signals/#defining-and-sending-signals – Clément Denoix Nov 22 '17 at 06:31

1 Answers1

6

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()
Saji Xavier
  • 2,132
  • 16
  • 21