更新用户和自定义用户模型中的电子邮件字段

时间:2018-01-27 22:48:17

标签: python django

创建帐户时,我有一个由2个表单组成的注册表单,从中可以在User和Student模型中保存电子邮件字段。现在,我制作了更新帐户信息视图。问题是,我希望两种型号的电子邮件都会相同更新。但我得到错误:



'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)




0 个答案:

没有答案