简体   繁体   中英

Get email in another model after user is created in django

I am a beginner in django. When admin creates a user, I am trying to save some fields in EmailAddress model.But for some reason the email field is always blank. Is there any way I can update the instance with email in UserProfile or EmailAddress model.

models.py looks like this

User._meta.get_field('email').blank = False
User._meta.get_field('email')._unique = True


class EmailAddress(models.Model):
    user = models.OneToOneField(User, unique=True, related_name ='address')
    email = models.EmailField()
    verified = models.BooleanField(verbose_name=_('verified'), default=True)
    primary = models.BooleanField(verbose_name=_('primary'), default=True)

    class Meta:
        db_table = 'account_emailaddress'


class UserProfile(models.Model, HashedPk):
    user = models.OneToOneField(User, unique=True, related_name ='profile')
    job_title = models.CharField(max_length=128, blank=True, null=False, default="")
    website = models.URLField(max_length=255, blank=True, null=True)
    organisation = models.CharField(max_length=50, blank=True, null=True, default="")
    phone_number = PhoneNumberField( blank=True, null=True)


@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
        EmailAddress.objects.create(user=instance)

forms.py looks like this --

class SignUpForm(forms.Form):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +44)"))
    organisation = forms.CharField(max_length=50)
    email = forms.EmailField()
    password1 = forms.CharField(max_length=20)
    password2 = forms.CharField(max_length=20)
    captcha = ReCaptchaField(attrs={'theme' : 'clean'})


    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        up = user.profile
        up.phone_number = self.cleaned_data['phone_number']
        up.organisation = self.cleaned_data['organisation']
        user.save()
        up.save()

Any help is highly appreciated.

Sorted. It needs to be

EmailAddress.objects.create(user=instance, email=instance.email)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM