Django-allauth自定义usermodel错误

时间:2015-04-30 13:21:25

标签: django django-allauth

我的小Django项目遇到了一些问题。
我使用allauth登录用户,并且我想在登录时存储一些额外的信息,在这种特殊情况下,"功能"。我尝试像文档https://docs.djangoproject.com/en/1.8/topics/auth/customizing/中所解释的那样扩展User类 一切都很好,除非我尝试注册我收到错误(如下所述)。所以我的问题是如何存储我从UserProfile模型中的表单中获取的信息?

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()

我的settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'anmeldung.forms.SignupForm'  

错误:

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

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

感谢您的时间,祝您度过愉快的一天!

1 个答案:

答案 0 :(得分:0)

我认为不会保存...您无法将该功能保存到用户,因为该列存在于UserProfile中。请记住,UserProfile只是默认用户模型的扩展。

因此,在注册时,您需要创建一个UserProfile,如:

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()