您好我有以下Django模型
GenericIPAddressField
我假设django的GenericIPAddressField
做了一些字符串验证,字符串确实是一个有效的IP地址。我还阅读了django的源代码,它确实有一些与# Assume that *ap* is a valid AccessPoint instance
# Notice ip_address IS NOT A VALID IP ADDRESS
>> AccessPointIPAddress.objects.create(ap=ap, ip_address='xxxxxx123123----')
<AccessPointIPAddress: ap xxxxxx123123---- 2015-05-18 12:39:25.491811>
但是当我尝试在django的shell上运行它时:
xxxxxx123123----
由于给定的ip-address private bool insertIntoExcel(string pathname , string sheetname ,int excelRow, int excelColumn,string value)
{
try
{
Microsoft.Office.Interop.Excel._Application oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook mWorkBook = oXL.Workbooks.Open(pathname, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
Microsoft.Office.Interop.Excel._Worksheet mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item(sheetname);
Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;
mWSheet1.Cells[excelRow, excelColumn] = value;
}catch
{
return false;
}
return true;
}
不是有效的IP地址,我期待它会引发某种ValueError或验证错误。
我在这里遗漏了什么吗?或者django的这一部分被破坏了吗?目前正在使用Django 1.6.5
答案 0 :(得分:2)
https://docs.djangoproject.com/en/1.8/ref/validators/#how-validators-are-run
有关验证程序如何在表单中运行的详细信息,请参阅表单验证,以及验证对象在模型中的运行方式。请注意,保存模型时不会自动运行验证程序,但如果您使用的是ModelForm,它将在表单中包含的任何字段上运行验证程序。有关模型验证如何与表单交互的信息,请参阅ModelForm文档。
您可以覆盖save()方法并在模型实例上执行full_clean(),如此处的文档中所述: https://docs.djangoproject.com/en/1.8/ref/validators/#how-validators-are-run
或仅对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)
它将使用以下验证器:
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')
答案 1 :(得分:0)
被接受的答案对我不起作用;所以我查看了验证器的来源,发现了这些功能:
from django.core.validators import validate_ipv4_address
from django.core.exceptions import ValidationError
ip = "127.0.0.1"
try:
validate_ipv46_address(ip) # Success
except ValidationError:
print("Invalid")
也适用于其他类型:
validate_ipv4_address(ip)
validate_ipv6_address(ip)