在运行manage.py时获取此错误消息
在/ accounts / signup / teacher /'str'对象上的AttributeError没有 属性“添加”
这是我编写的代码-> forms.py
class TeacherSignUpForm(UserCreationForm):
email = forms.EmailField(max_length=100)
firstname = forms.CharField(max_length=100)
lastname = forms.CharField(max_length=100)
phonenumber = forms.IntegerField(required=True)
linkedin = forms.URLField(max_length=200)
class Meta(UserCreationForm.Meta):
model = User
def save(self, commit=True):
user = super().save(commit=False)
user.is_teacher = True
if commit:
user.save()
mentor = Mentor.objects.create(user=user)
mentor.email.add(*self.cleaned_data.get('email'))
mentor.firstname.add(*self.cleaned_data.get('firstname'))
mentor.lastname.add(*self.cleaned_data.get('lastname'))
mentor.phonenumber.add(*self.cleaned_data.get('phonenumber'))
mentor.linkedin.add(*self.cleaned_data.get('linkedin'))
return user
models.py
#mentor model
class Mentor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
email = models.EmailField(max_length=100)
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
linkedin = models.URLField(max_length=200,null=True,blank=True)
phonenumber = models.IntegerField(null=True,unique=True)
和观看次数
class TeacherSignUpView(CreateView):
model = User
form_class = TeacherSignUpForm
template_name = 'registration/signup_form.html'
def get_context_data(self, **kwargs):
kwargs['user_type'] = 'teacher'
return super().get_context_data(**kwargs)
def form_valid(self, form):
user = form.save()
login(self.request, user)
return redirect('teachers:app-instructor-dashboard')
当我尝试以导师/老师的身份登录时,收到此错误消息。然后应该将我重定向到app-instructor-dashboard
答案 0 :(得分:1)
您的看法没有多大意义。 EmailField
和UrlField
与CharField
差不多,但需要额外验证。这些是电子邮件的 not 集合(列表等)。
因此,您应该分配以下值:
class TeacherSignUpForm(UserCreationForm):
email = forms.EmailField(max_length=100)
firstname = forms.CharField(max_length=100)
lastname = forms.CharField(max_length=100)
phonenumber = forms.IntegerField(required=True)
linkedin = forms.URLField(max_length=200)
class Meta(UserCreationForm.Meta):
model = User
def save(self, commit=True):
self.instance.is_teacher = True
user = super().save()
mentor = Mentor.objects.create(
user=user,
email=self.cleaned_data['email'],
firstname=self.cleaned_data['firstname'],
lastname=self.cleaned_data['lastname'],
phonenumber=self.cleaned_data['phonenumber'],
linkedin=self.cleaned_data['linkedin']
)
return user
请注意,有必要先 保存user
对象。在数据库端不是创建的User
对象不能用于创建Mentor
对象,因为它没有主键可以使用。>