根据其他字段验证表单

时间:2013-10-16 10:05:23

标签: django-forms django-validation

我有这样的表格:

class NetworkInput(forms.Form):          
    IP = forms.GenericIPAddressField()     
    Netmask = forms.IntegerField()

用户应该能够输入IPv4或IPv6地址。 根据IP版本,Netmask的验证应如下所示:

import ipcalc
IP = ipcalc.IP(IP)
if IP.version() == 4:
    if Netmask > 29:
        raise ValidationError(u'%s is not big enough' % value)
else:
    if Netmask > 125:
        raise ValidationError(u'%s is not big enough' % value)

但在验证网络掩码时,我不知道如何访问变量IP。

1 个答案:

答案 0 :(得分:1)

正如https://docs.djangoproject.com/en/1.5/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

中的django文档所述

创建一个执行组合验证的clean()方法,例如

def clean(self):
    IP = self.cleaned_data['IP']
    Netmask = self.cleaned_data['Netmask']
    IP = ipcalc.IP(IP)
    if IP.version() == 4:
        if Netmask > 29:
            raise ValidationError(u'%s is not big enough' % value)
    else:
        if Netmask > 125:
            raise ValidationError(u'%s is not big enough' % value)