我有2个帐户(教师和学生),它们都扩展了CustomUser模型。讲师有一个电子邮件字段。学生具有从下拉菜单中选择的讲师键。
我可以用讲师的电子邮件填充ModelChoiceField,没问题。但是,我现在无法将所选教师的电子邮件适当地保存到外键中。我认为错误在于我如何保存教师ID,特别是这一行,
student.instructor_id = Instructor.objects.get(email=self.cleaned_data["instructor_id"])
,但是我不确定是什么问题。请帮忙!
forms.py
class StudentSignUpForm(UserCreationForm):
instructor_id = forms.ModelChoiceField(queryset=Instructor.objects.all())
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'inGameName', 'instructor_id')
help_texts = {
'username': 'Required',
'inGameName': 'Required; A name by which you can be identified',
'instructor_id': 'Optional; Provided by your professor',
}
@transaction.atomic
def save(self):
user = super().save(commit=False)
user.is_student = True
student = Student.objects.create(user=user)
student.instructor_id = Instructor.objects.get(email=self.cleaned_data["instructor_id"])
student.save()
user.save()
return user
class InstructorSignUpForm(UserCreationForm):
email = forms.EmailField(label='Your Email', help_text='Required')
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ('username', 'inGameName', 'email')
help_texts = {
'username': 'Required',
'inGameName': 'Required; A name by which you can be identified',
}
@transaction.atomic
def save(self):
user = super().save(commit=False)
user.is_instructor = True
instructor = Instructor.objects.create(user=user)
instructor.email = self.cleaned_data["email"]
instructor.save()
user.save()
return user
models.py
from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager
from django.db import models
class UserManager(AbstractUserManager):
pass
class CustomUser(AbstractUser):
objects = UserManager()
is_student = models.BooleanField(default=False)
is_instructor = models.BooleanField(default=False)
username = models.CharField(max_length=40, primary_key=True, default='')
inGameName = models.CharField("In-Game Name", max_length=40, default='')
USERNAME_FIELD = 'username'
class Instructor(models.Model):
user = models.OneToOneField(CustomUser, default='USER', on_delete=models.CASCADE)
email = models.EmailField(max_length=254, unique=True, default='')
def __str__(self):
return self.email
class Student(models.Model):
user = models.OneToOneField(CustomUser, default='USER', on_delete=models.CASCADE)
instructor_id = models.ForeignKey(Instructor, to_field='email', on_delete=models.CASCADE, default='')