Search code examples
djangodjango-modelsdjango-allauth

Does Django have a way to do something only at the time of user creation (and not every save)?


I am trying to get around difficulty bulk importing users with user info via django allauth social login. I am doing this by creating a separate model which I can csv upload user information to, which will be ported over to the real table after the user logs in for the first time. Essentially, it will pre-populate the user's information for them based on their email. The issue I am running into is that because I am using a post_save sender, it is trying to update the information every time the user changes an aspect of their profile. My issue with this is in the case where user information legitimately changes, but it wasn't updated in the UserData table (which is only meant to be used for initial import), it will simply change back. I am curious for any ideas to get around this. Thanks!

@receiver(post_save, sender=User)
def imported_info_update(sender, instance, **kwargs):
    imported_info = UserData.objects.get(email=instance.email)
    job = Jobs.objects.get(job=imported_info.department)
    location = Locations.objects.get(location=imported_info.team)
    school = Schools.objects.get(school=imported_info.school)
    UserProfile.objects.update_or_create(user_id=instance.id,
                                       job=job,
                                       location=location,
                                       school=school)

Solution

  • Try this

    @receiver(post_save, sender=User)
    def imported_info_update(sender, instance=None, created=False, **kwargs):
        if created:
            imported_info = UserData.objects.get(email=instance.email)
            job = Jobs.objects.get(job=imported_info.department)
            location = Locations.objects.get(location=imported_info.team)
            school = Schools.objects.get(school=imported_info.school)
            UserProfile.objects.update_or_create(user_id=instance.id,
                                                 job=job,
                                                 location=location,
                                                 school=school)

    Reference: https://docs.djangoproject.com/en/2.0/ref/signals/#post-save