0
votes

Im having some problems with my little Django project.
Im using allauth to log users in and also I would like to store some additional information on login, in this particular case the "function". I tried to extend the User class like explained in the docs https://docs.djangoproject.com/en/1.8/topics/auth/customizing/
Everything is fine except when I try to signup I'm getting the error (explained below). So my question is how do I store the information I'm getting from the forms in the UserProfile model?

my models.py

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

class UserProfile(models.Model):

    user = models.OneToOneField(User, related_name='profile', unique=True)
    function = models.CharField("Function", max_length=150, blank=False)

my forms.py

from django import forms

class SignupForm(forms.Form):
    first_name = forms.CharField(max_length=35, label='First name')
    last_name = forms.CharField(max_length=35, label='Last name')
    function = forms.CharField(max_length=35, label='Function')

def signup(self, request, user):
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.function = self.cleaned_data['Function']
    user.save()

my settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'anmeldung.forms.SignupForm'  

the error:

in this line:    user.function = self.cleaned_data['Function']

Exception Type: KeyError at /accounts/signup/
Exception Value: 'Function'

Thanks for your time and have a nice day!

1

1 Answers

0
votes

I don't think that's going to save... You can't save the function to User, because the column exists in UserProfile. Remember, UserProfile is just an extension of the default User model.

So, in signup, you'd want to create a UserProfile like:

def signup(self, request, user):
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    function = self.cleaned_data['function']
    # Save the default User fields first, so you can get the User instance
    user.save()
    # Use the created 'user' to create a UserProfile 
    userprofile = UserProfile(user=user, function=function)
    userprofile.save()