How to you pass a validation error to a template

只愿长相守 提交于 2019-12-02 06:15:34

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