Solution for How to add more fields in django-allauth User model?
is Given Below:
I want to add more fields in Django allauth user model. I created a User-Profile model in a one-to-one relation with auth-user and tried to create user-profile object in form.py. But this method is not working.
According to this doc(https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model) I tried to extend the User model. But after signup I didn’t get any data in ‘UserProfile’.
Here is my code:
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="userprofile", on_delete=models.CASCADE)
profile_picture = models.ImageField()
forms.py
class CustomSignupForm(SignupForm):
profile_picture = forms.ImageField()
def signup(self, request, user):
up = user.userprofile
user.userprofile.profile_picture = self.cleaned_data['profile_picture']
up.profile_picture = self.cleaned_data['profile_picture']
user.save()
up.save()
return user
Visit the the below allauth doc page:
https://django-allauth.readthedocs.io/en/latest/advanced.html#custom-user-models
class CustomSignupForm(SignupForm):
profile_picture = forms.ImageField()
this only work when you have that table in database, let’s say for registration form you want email in your form, you don’t need to add email in models because it’s already in database, so you can call it in forms.py by
email = forms.EmailField()
or first_name and last_name, for your code you HAVE to add this in models because there is no table in database for that
take a look at my code maybe it will help you
note: I’m not using allauth
models.py
def upload_to(instance, filename):
profile_image_name="profile_images/userID_{0}/profile.jpg".format(instance.user.id)
full_path = os.path.join(settings.MEDIA_ROOT, profile_image_name)
if os.path.exists(full_path):
os.remove(full_path)
return profile_image_name
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=CASCADE)
profileimage = FileField(default="default.jpg", upload_to=upload_to, blank=True)
user_bio = models.TextField(max_length=300, blank=True,null=True)
forms.py
class ProfileImageUpdate(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['profileimage', 'user_bio']