Django - 扩展的用户模型没有保存

时间:2016-04-22 14:00:07

标签: python django django-forms django-registration

我在尝试从扩展用户模型中保存数据时遇到了麻烦。

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应用程序中的注册表保存Customer的属性。但是使用我当前的代码,它只会保存“用户”属性。当我尝试将表单模型更改为“客户”时,它不会保存“用户”属性。

1 个答案:

答案 0 :(得分:0)

这是因为User是OnetoOnefield,因此您需要创建用户,保存它,然后将其添加到Customer对象并保存。

您需要在forms.py中执行类似的操作,重新定义保存方法:

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

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