如何检查Django验证器中是否存在URL? [英] How can I check if a URL exists with Django’s validators?

查看:280
本文介绍了如何检查Django验证器中是否存在URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 如果URL_THAT_POINTS_TO_SOME_PDF存在
SHOW_SOMETHING


解决方案

编辑:请注意,这不再适用于任何版本的Django以上1.5



我假设您要检查文件是否真实存在,而不是如果只有一个对象(这只是一个简单的if语句)



首先,我会建议始终查看Django的源代码,因为你将找到一些你可以使用的伟大的代码:)



我假设你想在模板中这样做。没有内置的模板标签来验证网址,但您可以在模板标签中基本使用 URLValidator 类来测试它。简单地:

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

validate = URLValidator(verify_exists = True)
try:
validate('http://www.somelink.com/to/my.pdf')
除了ValidationError,e :
打印e

URLValidator class将不能打开链接时,会吐出 ValidationError 。它使用 urllib2 实际打开请求,所以它不只是使用基本的正则表达式检查(但它也是这样做的。)



您可以将其转换成自定义模板标签,您可以在django文档中找到如何创建文档,并关闭。



希望这是一个开始你。


I want to check in django if a URL exists and if it does I want to show something on screen, i.e.:

if URL_THAT_POINTS_TO_SOME_PDF exists 
     SHOW_SOMETHING

解决方案

Edit: Please note, this is no longer valid for any version of Django above 1.5

I assume you want to check if the file actually exists, not if there is just an object (which is just a simple if statement)

First, I will recommend always looking through Django's source code because you will find some great code that you could use :)

I assume you want to do this within a template. There is no built-in template tag to validate a URL but you could essentially use that URLValidator class within a template tag to test it. Simply:

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

validate = URLValidator(verify_exists=True)
try:
    validate('http://www.somelink.com/to/my.pdf')
except ValidationError, e:
    print e

The URLValidator class will spit out the ValidationError when it can't open the link. It uses urllib2 to actually open the request so it's not just using basic regex checking (But it also does that.)

You can plop this into a custom template tag, which you will find out how to create in the django docs and off you go.

Hope that is a start for you.

这篇关于如何检查Django验证器中是否存在URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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