Django-allauth and modelforms

It took me a ridiculously long and frustrating time to work out how to do this, so I’m documenting what I’ve done in the hope that it helps someone else. If you want to extend the Django user model (to create a user profile, as described in the docs https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model) to create a user profile, and to still use Django-allauth you might as well give up on the documentation: it’s not going to help you. But what you need to do is fairly simple:

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)

forms.py

class SignupForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('first_name', 'last_name', 'phone', 'type')

    # A custom method required to work with django-allauth, see https://stackoverflow.com/questions/12303478/how-to-customize-user-profile-when-using-django-allauth
    def signup(self, request, user):
        # Save your user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

        # Save your profile
        profile = Profile()
        profile.user = user
        profile.phone = self.cleaned_data['phone']
        profile.type = self.cleaned_data['type']
        profile.save()

settings.py

# Required by django-allauth to extend the sign up form to include profile data
ACCOUNT_SIGNUP_FORM_CLASS = 'core.forms.SignupForm'

I’m not sure why I thought that django-allauth would take care of saving user profiles when it very explicitly says it doesn’t do anything apart from authentication. I suppose we should count ourselves lucky that it’s easy to extend the form to include additional profile fields.

11 thoughts on “Django-allauth and modelforms

  1. ofey

    Hi I Googled ‘allauth frustration’ and arrived here. Glad to see someone else having difficulty with the documentation, it is terrible, really difficult to use. I wish they would give examples and show how to set templates for signin and signup. So my problem isn’t the same as yours but thanks for posting anyway.

    Reply
  2. Kim

    Thanks a lot. Your code was clean and efficient. After several hours of struggling to add extra fields to Profile, I rechecked yours. You saved my day, or more. -k

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>