How to you pass a validation error to a template

落爺英雄遲暮 提交于 2019-12-02 09:15:53

问题


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,


回答1:


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


来源:https://stackoverflow.com/questions/17105947/how-to-you-pass-a-validation-error-to-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!