首页 > 解决方案 > 无法在 Django 的 UserCreationForm 中引发错误?

问题描述

我想在我的 UserCreationForm 中提出错误。我已经看过有关此问题的先前问题,但这对我不起作用。我给了现有的电子邮件,当我提交时,页面上没有错误显示。你能找出我的错误吗?

我是如何在 forms.py 中编写的

class StudentRegisterForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = ['email', ....]
    
    def __init__(self, *args, **kwargs):
        email_attr = {'class': 'form-control', 'id': 'email-register', 'type': 'email'}

        super(StudentRegisterForm, self).__init__(*args, **kwargs)
        self.fields['email'].widget.attrs.update(email_attr)
        # some other fields

    def clean_email(self):
        email = self.cleaned_data.get('email')
        
        if CustomUser.objects.filter(email=email).exists():
            raise forms.ValidationError("Email's already taken!")
        return email

视图.py

class StudentRegisterView(SuccessMessageMixin, CreateView):
    template_name = "attendance/login-register/student_register.html"
    form_class = StudentRegisterForm
    success_url = "/"

标签: django

解决方案


推荐阅读