Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Custom Form Validation IP address and Domain name

Tags:

python

django

Im just writing a form. However I want to perform custom validation on the hostname. That if type = A then validate that it is a domain name other wise if it is type = PTR validate it is an IP address. Would this logic be done within the form or the view ?

RECORD_CHOICES = (
     ('A','A'),
     ('Cname','CNAME'),
     ('PTR', 'PTR'),
    )

class CacheCheck(forms.Form):
    type = forms.TypedChoiceField(choices=formfields.TYPE_CHOICES, initial='FIXED')
    record = forms.TypedChoiceField(choices=formfields.RECORD_CHOICES, initial='FIXED')
    hostname = forms.CharField(max_length=100)

    def clean(self):  
        cleaned_data = super(CacheCheck, self).clean()
        record = cleaned_data.get("record")

        if record == "PTR":
            hostname = forms.GenericIPAddressField(label=("ip address"))
        else record == "A":
            hostname = forms.RegexField(label=("hostname"), max_length=31, regex=r'[a-zA-Z0-9-_]*\.[a-zA-Z]{2,6}'

Also the forms.Form that is passed to the CacheCheck class is this a form of mixin or subclassing ?

like image 220
felix001 Avatar asked Jun 13 '13 16:06

felix001


1 Answers

Write a clean() method for your form. See the Django docs on cleaning and validating fields that depend on each other for more information.

Your clean method should return the cleaned_data dictionary. Inside the cleaned method, you cannot instantiate new form fields, but you can validators.

from django.core.validators import validate_ipv46_address, RegexValidator

validate_hostname = RegexValidator(regex=r'[a-zA-Z0-9-_]*\.[a-zA-Z]{2,6}')

def clean(self):  
    cleaned_data = super(CacheCheck, self).clean()
    record = cleaned_data.get("record")
    hostname = cleaned_data.get(hostname, "")

    if record == "PTR":
        validate_ipv46_address(hostname)
    elif record == "A":
        validate_hostname(hostname)
        # todo: check length of hostname as well

    return cleaned_data

To answer your other question, your CacheCheck class is a subclass of forms.Form.

like image 190
Alasdair Avatar answered Sep 22 '22 07:09

Alasdair