Django GenericIPAddress field is not validating input

元气小坏坏 提交于 2019-12-04 18:48:10

https://docs.djangoproject.com/en/1.8/ref/validators/#how-validators-are-run

See the form validation for more information on how validators are run in forms, and Validating objects for how they’re run in models. Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form. See the ModelForm documentation for information on how model validation interacts with forms.

You can override save() method and do a full_clean() on the model instance as described in the docs here: https://docs.djangoproject.com/en/1.8/ref/validators/#how-validators-are-run

or only use validator for GenericIPAddressField:

from django.core.validators import ip_address_validators
from django.core.exceptions import ValidationError

def save(self, *args, **kwargs):
    try:
        ip_address_validators('ipv4', self.ip_address)
    except ValidationError:
        return
    super(AccessPointIPAddress, self).save(*args, **kwargs)

it will use the following validator:

ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$')
validate_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!