表单类中 clean 方法所需的 Django 字段
我想在表单文件的 clean 方法中重新定义字段的必需属性:
class NewUserFullForm(NewUserForm):
REGEX_PHONE = '^(\+[0-9]{2})[ \.\-]?[0-9][ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}$'
phone = forms.RegexField(REGEX_PHONE, help_text='Ex : +33 1 34 12 52 30')
fax = forms.RegexField(REGEX_PHONE, help_text='Ex : +33 1 34 12 52 30', required=False)
gsm = forms.RegexField(REGEX_PHONE, help_text='Ex : +33 6 34 12 52 30', required=False)
def clean(self):
if self.cleaned_data["asso_waldec"] == True:
self.fields['phone'].required = True
但我的 clean 方法不起作用
I want to redefine the required attribute for a field in a clean method of my form file:
class NewUserFullForm(NewUserForm):
REGEX_PHONE = '^(\+[0-9]{2})[ \.\-]?[0-9][ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}
But my clean method doesn't work
phone = forms.RegexField(REGEX_PHONE, help_text='Ex : +33 1 34 12 52 30')
fax = forms.RegexField(REGEX_PHONE, help_text='Ex : +33 1 34 12 52 30', required=False)
gsm = forms.RegexField(REGEX_PHONE, help_text='Ex : +33 6 34 12 52 30', required=False)
def clean(self):
if self.cleaned_data["asso_waldec"] == True:
self.fields['phone'].required = True
But my clean method doesn't work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嘿!你看过 htis 文档/示例吗:
Django 验证
也许这个会清除它。
Hey! Have you looked at htis document/examples:
Django Validation
Maybe this will clear it up.
一个问题是 clean 函数必须返回已清理数据的完整集合(请参阅 文档)。我相信您应该检查“电话”是否为空并提出描述问题的“验证错误”,而不是更改“必需”属性。
另外,由于您的表单继承自“NewUserForm”,您应该调用
super(NewUserFullForm, self).clean()
确保继承的字段也被清理。One problem is that the clean function has to return the full collection of cleaned data (see docs). Rather than changing the 'required' attribute I believe you should do the check to see if 'phone' is blank and raise a 'ValidationError' describing the problem.
Also since your form inherits from 'NewUserForm' you should call
super(NewUserFullForm, self).clean()
to ensure that the inherited fields are cleaned as well.