Denny Crane
Denny Crane

Reputation: 659

Validate form depending on another field

I have this form:

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

The users should be able to enter an IPv4 or an IPv6 address. Depending of the IP version the validation of Netmask should look like this:

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)

But I don't know how to access the variable IP when validating the Netmask.

Upvotes: 0

Views: 400

Answers (1)

Jonas Reichert
Jonas Reichert

Reputation: 118

As explained in the django docs at https://docs.djangoproject.com/en/1.5/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

create a clean() method that does the combined validation, e.g

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)

Upvotes: 1

Related Questions