Skip to content Skip to sidebar Skip to footer

Django Allauth Saving Custom User Profile Fields With Signup Form

I am a beginner in Django. I am using Django 1.10 with an allauth app to create a user registration. There are couple of extra fields (phone_number and organization) which I have i

Solution 1:

In your model UserProfile,

user = models.OneToOneField(User, unique=True)

this means, you need to access the profile like request.user.userprofile, so either you can add a related_name in your model field and migrate,

user = models.OneToOneField(User, unique=True related_name='profile')

Or you may need to change profile to userprofile in your form,

Either way, I suppose if the user has no UserProfile yet created then, you may need to change your form,

def signup(self, request, user):
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.save()
    profile, created = models.UserProfile.objects.get_or_create(user=user)
    profile.phone_number = self.cleaned_data['phone_number']
    profile.organisation = self.cleaned_data['organisation']
    profile.save()

Solution 2:

Added the following code in models.py

#Other imports
from phonenumber_field.modelfields import PhoneNumberField

class UserProfile(models.Model, HashedPk):
    user = models.OneToOneField(User, unique=True, related_name ='profile')
    organisation = models.CharField(max_length=50, blank=True, null=True)
    phone_number = PhoneNumberField( blank=True, null=True)

Changed the following code in forms.py(Got help from @zaidfazil)

def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        """
        profile, created = models.UserProfile.objects.get_or_create(user=user)
        profile.phone_number = self.cleaned_data['phone_number']
        profile.organisation = self.cleaned_data['organisation']
        profile.save()
        user.save()
        """
        up = user.profile
        up.phone_number = self.cleaned_data['phone_number']
        up.organisation = self.cleaned_data['organisation']
        user.save()
        up.save()

The solution may not be the cleanest one but it works. If you have any other ways to do this then please let me know.


Post a Comment for "Django Allauth Saving Custom User Profile Fields With Signup Form"