gpt4 book ai didi

python - str 没有在 django 中添加对象

转载 作者:行者123 更新时间:2023-12-01 06:38:11 25 4
gpt4 key购买 nike

运行manage.py时收到此错误消息

AttributeError at /accounts/signup/teacher/ 'str' object has no attribute 'add'

这是我写的代码->表单.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

模型.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)

和 View

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

最佳答案

你的观点没有多大意义。 EmailFieldUrlField 与带有一些额外验证的 CharField 没什么区别。这些不是电子邮件的集合(列表等)。

因此,您应该分配如下值:

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
<b>user = super().save()</b>
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 对象,因为它没有主键一起工作。

关于python - str 没有在 django 中添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59569281/

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