Django多用户注册报错:DoctorProfile需关联Doctor实例
Django 用户类型注册报错解决
报错信息
ValueError: Cannot assign "<User: salman>": "DoctorProfile.user" must be a "Doctor" instance.
问题根源
- 信号绑定错误:你将
create_profile函数绑定到了User模型的post_save信号上。当User实例创建时,信号尝试用User对象初始化DoctorProfile,但DoctorProfile.user字段关联的是Doctor模型而非User,类型不匹配直接触发报错。 - DoctorProfile模型存在语法与字段缺失:代码中有多余的
}符号,且save方法用到的slug和name字段未定义,会导致额外运行错误。 - 逻辑关联混乱:
Doctor已经是User的一对一扩展模型,DoctorProfile又关联Doctor,若仅为扩展医生信息,可考虑合并或调整层级。
修复方案
1. 修正信号绑定目标
将信号的发送者从User改为Doctor,只有当Doctor实例创建时,才触发DoctorProfile的创建:
def create_profile(sender, **kwargs): if kwargs['created']: DoctorProfile.objects.create(user=kwargs['instance']) # 绑定到Doctor模型的post_save信号 post_save.connect(create_profile, sender=Doctor)
2. 修复DoctorProfile模型的语法与字段
补充缺失的字段并修正语法错误:
from django.utils.text import slugify class DoctorProfile(models.Model): user = models.OneToOneField(Doctor, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=100) # 补充save方法依赖的name字段 slug = models.SlugField(unique=True, blank=True) # 补充save方法依赖的slug字段 def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name
3. 优化用户类型自动创建逻辑(可选)
若需要在创建User时自动生成对应的Doctor/Patient实例,可新增信号处理:
def create_user_type(sender, **kwargs): if kwargs['created']: user = kwargs['instance'] if user.is_doctor: Doctor.objects.create(user=user) elif user.is_patient: # 根据实际需求给Patient的name字段赋值,这里用用户名示例 Patient.objects.create(user=user, name=user.username) post_save.connect(create_user_type, sender=User)
调整后流程通顺:创建标记为医生的User→自动生成Doctor实例→触发Doctor的post_save信号创建DoctorProfile,完全匹配字段的类型要求。
内容的提问来源于stack exchange,提问作者Rachid Mayene
相关产品推荐
相关产品推荐

