felix001
felix001

Reputation: 16691

How to you pass a validation error to a template

I have a IP validation rule such as :

>>> validate_ipv46_address("1.1.1")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/django/core/validators.py", line 125, in validate_ipv46_address
    raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
ValidationError: [u'Enter a valid IPv4 or IPv6 address.']

And I have a form that is currently functioning like...

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

    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)

        return cleaned_data

However there are a few things Im unclear on. Currently If i enter an incorrect IP it still passes me back the cleaned data. So what does the cleaned_data method actually do ? Also how would I pass any validation errors back to the template ?

Thanks,

Upvotes: 1

Views: 942

Answers (1)

Alp
Alp

Reputation: 29739

According to the django documentation your code should work and display "an error message at the top of the form". It won't display the error at the correct input element though.

There is also an alternative approach you could try. Assumed that validate_ipv46_address() and validate_hostname() just return a boolean instead of raising an exception:

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

    if record == "PTR" and not validate_ipv46_address(hostname):
        msg = "Enter a valid IPv4 or IPv6 address."
    elif record == "A" and not validate_hostname(hostname):
        msg = "Enter a valid hostname."

    if msg:            
        self._errors["hostname"] = self.error_class([msg])
        del cleaned_data["hostname"]

    return cleaned_data

Upvotes: 1

Related Questions