[Fixed]-Cleanest Way to Allow Empty Scheme in Django URLField


You could subclass the URLValidator and prefix schemeless values with http:// before calling super(). This avoids any duplication of code from URLValidator.

from django.core.validators import URLValidator

class OptionalSchemeURLValidator(URLValidator):
    def __call__(self, value):
        if '://' not in value:
            # Validate as if it were http://
            value = 'http://' + value
        super(OptionalSchemeURLValidator, self).__call__(value)

Leave a comment