我在表单中有一个字段“phone”,是用 ModelForm 创建的。我想验证这个字段。这是 models.py 中的代码:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
phone = models.CharField(max_length=20, validators=[validate_phone])
表单.py:
class UserProfileResetForm(ModelForm):
class Meta:
model = UserProfile
exclude = ('user')
到目前为止,根据我的了解,有几种方法可以验证从 Django 中的 ModelForm 创建的表单。我至少看到了其中的 3 个: 1. 将 UserProfileResetForm 中的电话覆盖为 RegexField 2.使用验证器(就像我现在做的) 3. 在UserProfileResetForm中创建clean_phone方法
所以我有点困惑......最好的方法是什么?
请您参考如下方法:
做你现在正在做的事。如果你有一个可以放在模型上的验证器,那么它不仅会验证你所有的模型形式,而且还会在管理界面中执行验证。如果仅在存在特定验证时覆盖模型表单中的 clean_phone,则您只需要在该表单中执行。您可以将该验证器放置的级别越低,您的应用程序(和数据)就越一致。
