For registration and authorization, I used the standard User model, where there are email , password fields. But now I need to add the ability to register users by phone number. That is, add a phone field.

Is it possible to implement this without losing data? And how to implement it? Google did not find a topic of interest to me or did not correctly formulate its own question. Would appreciate resources

  • incorrectly formulated a question, add a phone field to the table, include it in your model and fill in as existing fields - Eugene Dennis
  • Do you plan to use a phone number instead of mail for authorization / registration, or just want to add this field as an additional one? - floydya
  • Yes, I want to add a new phone field. - DevOma

1 answer 1

To models:

 from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') phone = models.TextField(max_length=24, blank=True) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() 

You can call the phone through: user.profile.phone , where user is a user object. In the same way, to the user, having a profile: profile.user .

Remember to create and execute the migrations.

Most likely you will not have profiles for already created users. To do this, run the shell: python manage.py shell and follow these steps:

 from django.contrib.auth.models import User from Π½Π°Π·Π²Π°Π½ΠΈΠ΅_прилоТСния.models import Profile # Π·Π°ΠΌΠ΅Π½ΠΈΡ‚Π΅ Π½Π°Π·Π²Π°Π½ΠΈΠ΅_прилоТСния Π½Π° вашС for user in User.objects.all(): # послС Π²Π²ΠΎΠ΄Π° этой строки Π΄ΠΎΠ±Π°Π²ΡŒΡ‚Π΅ Ρ‚Π°Π±ΡƒΠ»ΡΡ†ΠΈΡŽ Profile.objects.get_or_create(user=user) # Π½Π°ΠΆΠΌΠΈΡ‚Π΅ Π΄Π²Π°ΠΆΠ΄Ρ‹ Enter