我的Django模型是這樣的:如何在Django中爲模型字段編寫驗證器?
class Host():
ipv4 = models.ChaField(max_length=39,verbose_name=_("IPv4"), validator= [ip_validator])
ipv6 = models.CharField(max_length=39, verbose_name=_("IPv6"),
blank=True, null=True, validators= [ip_validator])
和我utils.py定義的ip_validator方法:
from netaddr import *
def ip_validator(value):
try:
ip_version = IPAddress(value).version()
if ip_version !=6:
raise ValidationError(u'%s Not a IPv6 address' % value)
except ValueError:
raise ValidationError(u'%s Not a IPv6 address' % value)
它工作正常,但我必須寫IPv4的驗證方法相同。這似乎是冗餘而不是一個好主意。是否有可能爲IPv4和IPv6編寫通用方法。
我發現下面的示例做,但無法理解它是如何傳遞的參數來驗證:
#!/usr/bin/env python
class IPAddress(object):
def __init__(self, version):
self.version = version
def validator_factory(ip_version):
def validate_ip_address(ip_address):
if ip_address.version != ip_version:
print "Invalid! :("
else:
print "Valid! :D"
return validate_ip_address
ipv4_validator = validator_factory(4)
ipv6_validator = validator_factory(6)
ipv4_address = IPAddress(4)
ipv6_address = IPAddress(6)
ipv4_validator(ipv4_address)
ipv4_validator(ipv6_address)
ipv6_validator(ipv6_address)
如果這樣做那麼我們必須在validator = []
已更新! 在models.py:
class Host():
ipv4 = models.CharField(max_length=39,verbose_name=_("IPv4 address"),
validators=[validator_factory(4)])
這是調用驗證程序的正確方法嗎? 和utils.py:
from netaddr import *
def validator_factory(ip_version):
def validate_ip_address(ipv4):
if IPAddress(ipv4).version != ip_version:
print "Invalid! :("
else:
print "Valid! :D"
return validate_ip_address
什麼是這裏的錯嗎?
Django的1.4已經在內置['GenericIPPAddressField'](https://docs.djangoproject.com/en/dev/ref/models/fields/#genericipaddressfield)。使用'protocol'參數可以接受IPv4,IPv6或兩種類型的地址。 – Alasdair
@Alasdair但我使用Django 1.3 –