如何将验证错误传递给模板

时间:2013-06-14 10:01:53

标签: django django-templates

我有一个IP验证规则,例如:

>>> 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.']

我有一个目前正在运作的表单......

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

然而,有一些事情我不清楚。目前如果我输入的IP不正确,它仍会将清理后的数据传回给我。那么cleaning_data方法实际上做了什么?我如何将任何验证错误传回模板?

谢谢,

1 个答案:

答案 0 :(得分:1)

根据django documentation您的代码应该工作并在表单顶部显示“错误消息”。但它不会在正确的输入元素上显示错误。

您还可以尝试另一种方法。假设validate_ipv46_address()validate_hostname()只返回一个布尔值而不是引发异常:

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