Automatically Adding Phone Field to Profile

Understanding Signal Handling and Profile Creation in Django User Registration Process, Automatically Adding Phone Field to Profile upon User Creation in Django

this is the user creating code in Django (views.py) -

myuser = User.objects.create_user(
                            user_details['username'], user_details['email'], user_details['pass1']
                        )
                        myuser.first_name= user_details['fname']
                        myuser.last_name= user_details['lname']
                        myuser.save()

after creating user profile will automatically created.
and here is signals code to create profile :

@receiver(post_save, sender=get_user_model())
def create_profile(sender, instance, created, **kwargs):
    if created:
        profile = Profile.objects.create(user=instance)
        profile.save()

and here is profile model :

class Profile(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    phone = models.CharField(max_length=20, blank=Ture)
     ....

so if the user creates an account, the profile will auto-create, but now i want to add a phone field automatically when the user creates his profile. What can I do?

Also, I did this -

myuser = User.objects.create_user(
                            user_details['username'], user_details['email'], user_details['pass1']
                        )
                        myuser.first_name= user_details['fname']
                        myuser.last_name= user_details['lname']
                        myuser.save()
                        
                        try:
                            pro_user = Profile.objects.get(user=user_details['username'])
                            pro_user.mobile = '12323232'
                            pro_user.save()
                        except Exception as tsturerr:
                            print(tsturerr) 

but it’s not work.

in short, i create user and then profile (by using signals).
but I want to save user mobile number also in profile.

Don’t use a signal for this.

Add the code to create the profile in the same view where you’re creating the user. That way you have the form data available to you to populate the profile fields.

Side note: Do not post your entire question in the title. Use the title field to provide the shortest possible identification of the issue, then post the details of that issue in the body of your message. (I’ve taken the liberty of editing this post for you.)

1 Like