如何将验证错误传递给模板 [英] How to you pass a validation error to a template

查看:68
本文介绍了如何将验证错误传递给模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然而,有一些事情不清楚。目前如果我输入一个不正确的IP,它仍然会传回我清理的数据。那么clean_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 ?

谢谢,

推荐答案

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

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.

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

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

这篇关于如何将验证错误传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆