我正在创建一个包含两种用户配置文件(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()
编辑:(基于Chris Pratt的建议)
表单的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)
答案 0 :(得分: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'])