Django 条件 URL 验证存在性

1 投票
1 回答
3857 浏览
提问于 2025-04-17 02:39

我在我的模型中定义了三个网址字段,具体如下:

image_1 = models.URLField(max_length=100, verify_exists=True, blank=True)
image_2 = models.URLField(max_length=100, verify_exists=True, blank=True)
image_3 = models.URLField(max_length=100, verify_exists=True, blank=True)

我想问的是,有没有办法测试一下 verify_exists 这个函数是返回 True 还是 False,如果有的话,我可以根据这个结果采取相应的行动吗?

1 个回答

5

Django的作用是使用URLValidator来检查一个网址是否有效。你可以使用在django.core中已有的相同验证方法。

编辑:举个例子,假设你想验证Django官方网站的链接https://www.djangoproject.com/是否存在,代码可以简单写成这样:

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


my_url_validator = URLValidator(verify_exists=True) #creates a URLValidator object with verify_exists.
my_url = "https://www.djangoproject.com/" #url to be verified   

#check if url is valid :)
try:                           
   my_url_validator(my_url) 
except ValidationError:
   #not valid!! :_( 
   #fix: custom stuff to the rescue :)     
   CustomStuff()...

撰写回答