Validate URL in Python & Django

From time to time we need to validate whether the URL is valid.

Of course, there is a quick hacky implementation of checking if the input string has the URL format, such as:

def valid_url(to_validate: str) -> bool:
    if to_validate.startswith("http"):
        # assume valid and move on...

...but let's make sure we do a better job than the above!


In Python 3, there is a urllib library and we can use its parse module (documentation), i.e.

from urllib.parse import urlparse

def valid_url(to_validate:str) -> bool:
    o = urlparse(to_validate)
    return True if o.scheme and o.netloc else False


Django comes with a variety of utility functions that will make your web development convenient. URLValidator module will help you validate whether the given URL is valid, and raise ValidationError exception if invalid:

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

def valid_url(to_validate:str) -> bool:
    validator = URLValidator()
        # url is valid here
        # do something, such as:
        return True
    except ValidationError as exception:
        # URL is NOT valid here.
        # handle exception..
        return False