Home > Software engineering >  How to update User model in Django using signals.py
How to update User model in Django using signals.py

Time:12-10

how can I update the user model first_name and last_name in Django using signals.py when a new user updates first_name and last_name in custom registration form?

This is my signals.py for creating a custom separate user details model using Django

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_profile_handler(sender, instance, created, **kwargs):
    if not created:
        return
    profile = models.Profile_user(user=instance, first_name=instance.first_name, last_name=instance.last_name, email=instance.email)
    profile.save()

Now I want to update the settings.AUTH_USER_MODEL when an new user update his first_name and last_name using custom register form

CodePudding user response:

As per your code above :

  1. In your models.py you have a Profile_user model which you are creating if a new AUTH_USER_MODEL instance is created.

Your requirement is if the Profile_user model is updated with first name and last name, you want to update the AUTH_USER_MODEL instance as well.

Solution: In signals.py

@receiver(post_save, sender=models.Profile_user)
def update_auth_user_model_handler(sender, instance, created, **kwargs):
    if created:
        return
    user_instance = instance.user
    user_instance.first_name = instance.first_name
    user_instance.last_name = instance.last_name
    user_instance.save()
  • Related