1

我有一个 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,它仍然会将清理后的数据传回给我。那么cleaned_data 方法实际上是做什么的呢?另外,我如何将任何验证错误传递回模板?

谢谢,

4

1 回答 1

1

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

您还可以尝试另一种方法。假设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
于 2013-06-14T10:13:59.837 回答