Question

I'm using a custom sign up form with django-allauth.

settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'project.userprofile.form.UserSignupForm'

form.py

from django import forms
from models import UserProfile

class UserSignupForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('mobile_number',)

models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    mobile_number = models.CharField(max_length=30, blank=True, null=True)

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

The User and the UserProfile objects are created, however the UserProfile isn't associated with any User object. It's late and I'm probably missing something silly, right?

UPDATE: As Kevin pointed out, the solution was to add the save method in the form.py. This is how it looks now:

from django import forms
from django.contrib.auth.models import User
from models import UserProfile

class UserSignupForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('mobile_number',)

    def save(self, user):
        profile = UserProfile(user=user)
        profile.mobile_number = self.cleaned_data['mobile_number']
        profile.save()
Was it helpful?

Solution

The documentation says:

[ACCOUNT_SIGNUP_FORM_CLASS] should implement a ‘save’ method, accepting the newly signed up user as its only parameter.

It looks like you haven't provided such a method, so the user never gets connected to the profile. And I think you're not seeing an error because ModelForm has a save(commit=True) method that happens to match this signature, even though it doesn't do what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top