我想要实现的是,我想将配置文件模型进一步扩展到教师或学生。在注册表单中,我添加了一个选择字段,用户可以选择他是教师还是学生。以下是我的模型结构。
class Profile(UserenaLanguageBaseProfile):
""" Default profile """
GENDER_CHOICES = (
(1, _('Male')),
(2, _('Female')),
)
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='profile')
gender = models.PositiveSmallIntegerField(_('gender'),
choices=GENDER_CHOICES,
blank=True,
null=True)
class Teacher(Profile):
profile = models.OneToOneField(Profile,
unique=True,
verbose_name=_('profile'),
related_name='teacher')
home_address = models.CharField(_('home_address'), max_length=255, blank=True)
home_phone = models.CharField(_('home_phone'), max_length=30, blank=True)
cell_phone = models.CharField(_('cell_phone'), max_length=30, blank=True)
experience = models.IntegerField(default = 0)
summary = models.TextField(_('summary'), max_length=500, blank=True)
class Student(Profile):
profile = models.OneToOneField(Profile,
unique=True,
verbose_name=_('profile'),
related_name='student')
grade = models.CharField(_('grade'), max_length=50, blank=True)
我将注册保存方法重写为:
def save(self):
new_user = super(SignupFormExtra, self).save()
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
new_user.save()
if self.cleaned_data['teacher_or_student'] == 'teacher':
teacher = Teacher(profile = new_user.get_profile())
teacher.save()
elif self.cleaned_data['teacher_or_student'] == 'student':
student = Student(profile = new_user.get_profile())
student.save()
return new_user
当调用teacher.save()或student.save()方法时,它会引发一个完整性错误“(1048,”列'user_id'不能为空“)”但我不是在这里创建一个新的用户实例我正在尝试将新创建的profile_id分配给教师或学生模型。我做错了吗?我该怎么办?
答案 0 :(得分:3)
正如错误所示,您无法创建Student
或Teacher
而没有user
,因为您已将其定义为不可为空的字段。
确保您已经通过了您已定义的new_user
课程。
# ...
new_user.save()
if self.cleaned_data['teacher_or_student'] == 'teacher':
teacher = Teacher(profile = new_user.get_profile(), user=new_user)
teacher.save()
elif self.cleaned_data['teacher_or_student'] == 'student':
student = Student(profile = new_user.get_profile(), user=new_user)
student.save()
答案 1 :(得分:2)
我可能错了,但你为什么要从Profile模型中继承你的模型(所以你已经有了一个“user”字段),并且在你再次获得Profile模型的“profile”OneToOneField字段之后呢?