【问题标题】:Django-allauth custom usermodel errorDjango-allauth 自定义用户模型错误
【发布时间】:2015-04-30 13:21:24
【问题描述】:

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

我的模型.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)

我的表单.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()

我的设置.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'

感谢您的宝贵时间,祝您有愉快的一天!

【问题讨论】:

    标签: django django-allauth


    【解决方案1】:

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

    因此,在注册时,您需要创建一个 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2013-09-22
      • 2017-04-08
      • 2013-07-12
      • 2021-01-25
      • 2016-03-13
      • 1970-01-01
      • 2017-07-13
      相关资源
      最近更新 更多