【问题标题】:How to make an Email Field in form.py a required field?如何使 form.py 中的电子邮件字段成为必填字段?
【发布时间】:2018-11-08 10:01:52
【问题描述】:

我尝试了几种方法,但似乎无法成功。

这是我的代码:

 class Meta:
        model = User
        # set fields to be used in registration form
        fields = ['username','email','password','password2']

    username = forms.CharField(required=True)
    email = forms.EmailField(required=True, max_length=100) <---
    password= forms.PasswordInput()
    password2=forms.PasswordInput()


# user email must be unique
def clean_email(self):
    email = self.cleaned_data.get('email')
    # check if account with email exists
    if email and User.objects.filter(email=email).exists():
        raise forms.ValidationError('Email address already exists')
    return email

有谁知道为什么 required=True 不能使其成为必填字段?

【问题讨论】:

  • 你应该调用super()来检查继承的验证,这将验证required=True

标签: python django content-management-system


【解决方案1】:

@WillemVanOnsem 在他对您的问题的评论中所说的内容,我将在此处对其进行扩展以使其更清楚:您应该调用 super().clean_email() 以确保运行该字段的所有默认验证。

def clean_email(self):
    email = super().clean_email()

    if email is not None:
        # check if account with email exists
        if User.objects.filter(email=email).exists():
            raise ValidationError('Email address already exists.')

    return email

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 2015-08-03
    • 2023-04-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    相关资源
    最近更新 更多