假设我有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)
将验证器添加到CharField
的validator
字段:
from django.core.validators import EmailValidator
emailvalidator = EmailValidator(message="invalid email")
class Subscription(models.Model):
address = models.CharField(max_length=255, validators=[emailvalidator])
但是你应该考虑用EmailField
代替