【问题标题】:Django - extended user model not savingDjango - 扩展用户模型不保存
【发布时间】:2016-08-16 04:55:19
【问题描述】:

我在尝试保存扩展用户模型中的数据时遇到问题。

model.py

class Person(models.Model):
"""
The 'user' field creates a link between the django-registration-redux's
default user and allows it to be extended through this model.
"""
user = models.OneToOneField(User)

# Person attributes
address = models.CharField(max_length=50)
town = models.CharField(max_length=50)
postcode = models.CharField(max_length=10)
phone_no = models.CharField(max_length=10, unique=True)

# Meta contains information about the class which is not a field.
class Meta:
    abstract = True


class Customer(Person):

# No extra attributes required for Customer.

def __str__(self):
    return self.user.username


class Staff(Person):

# Staff attributes
job_role = models.CharField(max_length=50)
medical_contact = models.CharField(max_length=50)
nation_insurance = models.CharField(max_length=50, unique=True)

def __str__(self):
    return self.user.username

forms.py

class UserProfileForm(RegistrationFormUniqueEmail):
address = forms.CharField(max_length=50)
town = forms.CharField(max_length=50)
postcode = forms.CharField(max_length=7)
phone_no = forms.CharField(max_length=10)

class Meta:
    model = User
    fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']

regbackend.py

class CustomRegistrationView(RegistrationView):
form_class = UserProfileForm

def register(self, form_class):
    new_user = super(CustomRegistrationView, self).register(form_class)
    user_profile = Customer()
    user_profile.user = new_user
    user_profile.address = form_class.cleaned_data['address']
    user_profile.town = form_class.cleaned_data['town']
    user_profile.postcode = form_class.cleaned_data['postcode']
    user_profile.phone_no = form_class.cleaned_data['phone_no']
    user_profile.save()

    return user_profile

所以我需要通过 django-registration-redux 应用程序中的注册表单保存客户的属性。但是,使用我当前的代码,它只会保存“用户”属性。当我尝试将表单模型更改为“客户”时,它不会保存“用户”属性。

【问题讨论】:

    标签: python django django-forms django-registration


    【解决方案1】:

    因为User是一个OnetoOnefield,所以你需要创建用户,保存,然后添加到你的Customer对象中保存。

    你需要在你的forms.py中做类似的事情,重新定义save方法:

    def save(self, commit=True):
        user = user.super(UserProfileForm, self).save()
        customer = Customer(user=user)
        customer.save()
    

    不要只是复制粘贴,只是你知道你必须先注册用户,然后将它添加到你的新对象,添加其他字段,然后保存。

    【讨论】:

    • 感谢您的回复,我现在有了它,因此它确实创建了一个很棒的 Customer 实例,但实际上仍然没有保存数据。我也知道这两个密码字段被称为“password1”和“password2”,但 create_inactive_user 抛出一个 KeyError 要求输入“密码”。再次感谢。
    猜你喜欢
    • 2017-10-20
    • 2016-10-12
    • 2011-02-28
    • 2013-12-06
    • 2018-01-21
    • 2012-09-06
    • 2018-04-24
    相关资源
    最近更新 更多