表单对象没有属性' email'在django

时间:2018-01-28 17:01:07

标签: python django

我有一个由2个表单组成的注册表单,用户和学生模型中的电子邮件字段都保存在该表单中。现在,我制作了更新帐户信息视图。问题是,我希望这两个模型中的电子邮件都会得到更新。但我得到错误:



'StudentEditForm' object has no attribute 'email'




这是我的代码:



class StudentEditForm(forms.ModelForm):
    email = forms.EmailField(required=False)
    name = forms.CharField(max_length=30)
    surname = forms.CharField(max_length=50)
    photo = forms.ImageField(required=False)
    phone = forms.CharField(max_length=15, required=False)

    class Meta:
        model = Student
        fields = ('email', 'name', 'surname', 'phone', 'photo')

class User(AbstractUser):
    pass


class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=30, null=True, blank=True, default=None)
    surname = models.CharField(max_length=50, null=True, blank=True, default=None)
    email = models.EmailField(unique=True, null=True, blank=True, default=None)
    student_ID = models.CharField(unique=True, max_length=14,
                                  validators=[RegexValidator(regex='^.{14}$',
                                                             message='The ID needs to be 14 characters long.')],
                                  null=True, blank=True, default=None)
    photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None)
    phone = models.CharField(max_length=15, null=True, blank=True, default=None)

    def __str__(self):
        return self.surname
        
 
User.student = property(lambda p: Student.objects.get_or_create(user=p)[0])

def profile_edit(request):
    user = request.user
    student = request.user.student
    if request.method != 'POST':
        form = StudentEditForm(instance=student)

    else:
        form = StudentEditForm(request.POST, instance=student)
        user.email = form.email
        form.save()
        return render(request, 'index.html')
    context = {
        "form": form,
    }
    return render(request, "registration/profile_edit.html", context)




同样,我需要我能够更新电子邮件字段。电子邮件将保存在用户电子邮件中,但我也希望将其保存到学生邮箱中。

2 个答案:

答案 0 :(得分:1)

致电form.is_valid(),然后使用form.cleaned_data['email'],请参阅https://docs.djangoproject.com/en/1.11/topics/forms/

答案 1 :(得分:0)

我必须添加

form.is_valid()

user.email = form.cleaned_data['email'] 

还要添加解决此问题的user.save()