0

我正在创建一个具有两种类型的用户配置文件(DoctorProfile 和 PatientProfile)的站点。每个扩展 UserProfile,它与 User 具有 OneToOneField 关系。

尝试通过 ModelForm 注册新用户时,遇到以下错误:

duplicate key value violates unique constraint "accounts_userprofile_user_id_key"
DETAIL:  Key (user_id)=(38) already exists.

这似乎在创建 PatientProfile 时发生,它尝试创建用户。但是,用户已经使用User.objects.create_user()

如何配置它以便我只能创建一次用户?

这是我的(精简版)forms.py:

class PatientProfileForm(ModelForm):
    supplied_email = forms.CharField(max_length=256, label="Email Address", required=True)
    supplied_password = forms.CharField(max_length=256, label="Password", required=True, widget=forms.PasswordInput())
    supplied_password_confirm = forms.CharField(max_length=256, label="Password (again)", required=True, widget=forms.PasswordInput())

    def save(self, profile_callback=None):
        master_patient_profile = MasterPatientProfile(user=User.objects.create_user(username=self.cleaned_data['supplied_email'], email=self.cleaned_data['supplied_email'], password=self.cleaned_data['supplied_password']))
        master_patient_profile.save()

models.py 的简化版本:

class UserProfile(models.Model):
    user = models.OneToOneField(User, null=True)
    address_line_1 = models.CharField(_('Address 1'), max_length=100)
    address_line_2 = models.CharField(_('Address 2'), max_length=100, blank=True)
    city = models.CharField(_('City'), max_length=50)
    state = models.CharField(_('State'), max_length=20)
    zipcode = models.CharField(_('ZIP Code'), max_length=5)

class PatientProfile(UserProfile):
    gender = models.ForeignKey(UserGender)
    phone_number = models.CharField(max_length=12)
    date_of_birth = models.DateField(null=True)

class DoctorProfile(UserProfile):
    specialty = models.ManyToManyField(DoctorSpecialty)
    professional_statement = models.TextField()

编辑:(基于克里斯普拉特的建议)

表单的save()方法现在看起来像这样:

new_user, created = User.objects.get_or_create(username=self.cleaned_data['supplied_email'], email=self.cleaned_data['supplied_email'])
    if created:
        new_user.set_password(self.cleaned_data['supplied_password'])

    master_patient_profile = MasterPatientProfile(user=new_user)
4

1 回答 1

2

不要使用create_user. 这纯粹是一种方便的方法,只对实际的User创建形式真正有用。

在其他任何地方,您都应该使用get_or_create. 唯一的缺点是您无法使用它设置密码,因此您需要分两步完成。

user, created = User.objects.get_or_create(username=self.cleaned_data['supplied_email'], email=self.cleaned_data['supplied_email'])
if created:
    user.set_password(self.cleaned_data['supplied_password'])
于 2012-06-12T15:03:07.213 回答