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
validator is legit website or scam website. URL checker is a free tool to detect malicious URLs including malware, scam and phishing links. Safe link checker scan URLs for malware, viruses, scam and phishing links.
To check whether the string entered is a valid URL or not we use the validators module in Python. When we pass the string to the method url() present in the module it returns true(if the string is URL) and ValidationFailure(func=url, …) if URL is invalid.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With