Change: Please note this is no longer valid for any version of Django above 1.5
I assume that you want to check if the file actually exists, and not if there is only an object (which is a simple if statement)
Firstly, I will recommend always looking at the source code of Django, because you will find great code that you could use :)
I assume you want to do this in a template. There is no built-in template tag to validate the URL, but you can use this URLValidator class inside the template tag to validate 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 a ValidationError when it cannot open the link. It uses urllib2 to actually open the request, so it doesnโt just use basic regex checking (but also does it).
You can add this to your custom template tag, which you will learn how to create in django documents, and you're done.
Hope this is the beginning for you.
Bartek Jul 03 '10 at 4:00 2010-07-03 04:00
source share