gpt4 book ai didi

python - Userena - 将 Profile 模型进一步扩展到两个不同的模型

转载 作者:太空狗 更新时间:2023-10-30 02:49:19 26 4
gpt4 key购买 nike

我想要实现的是,我想将配置文件模型进一步扩展到教师或学生。在注册表单中,我添加了一个选择字段,用户可以在其中选择他是老师还是学生。下面是我的模型结构。

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, “Column 'user_id' cannot be null”)”,但我不会在这里创建新的用户实例我正在尝试将新创建的 profile_id 分配给教师或学生模型。我做错了??我该怎么办?

最佳答案

正如错误所说,您不能在没有 user 的情况下创建 StudentTeacher,因为您已将其定义为不可空字段.

确保您将您定义的 new_user 传递给您的类(class)..

# ...
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()

关于python - Userena - 将 Profile 模型进一步扩展到两个不同的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8949176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com