验证字符字段是否为电子邮件



假设我有model:

class Subscription(models.Model):
    address = models.CharField(max_length=255)

然后创建form:

class SubscriptionForm(ModelForm):
    class Meta:
        model = Subscription
        fields = ['address']
    def clean_address(self):
        email = self.cleaned_data['address']
        #VALIDATE HERE IF IT IS EMAIL
        return email

我如何将电子邮件验证器应用到我的字段而不改变模型?

编辑:这可能吗?

您最好只在模型中设置验证器。添加验证器不会影响数据库,所以它并没有真正改变数据库模型。

但是如果你真的想调用验证器那就那样做

from django.core.validators import EmailValidator
def clean_address(self):
    email = self.cleaned_data['address']
    EmailValidator()(email)

将验证器添加到CharFieldvalidator字段:

from django.core.validators import EmailValidator
emailvalidator = EmailValidator(message="invalid email")
class Subscription(models.Model):
     address = models.CharField(max_length=255, validators=[emailvalidator])

但是你应该考虑用EmailField代替

相关内容

  • 没有找到相关文章

最新更新