Does any one know how to get rid of the 'http://' prefix in Django urlfield.
I mean when we define a field as urlfield and try to enter a url to it, django will automatically add 'http://' prefix to it if no schema provide. I don't want that prefix.
I try to remove it under clean_field and clean method. It doesn't work.
I dig into the source code. I saw that django add 'http://' in 'to_python' method under UrlField class.
Is there any way to override it to get rid of 'http://'?
Without a scheme prefix, a string can't be a true URL, and accordingly, the URLField
won't support it.
However, the URLField
is pretty much just a CharField
with a URLValidator
, so if you write a new SchemelessURLValidator
(derived from the built-in one) and add that to a normal CharField
, that should get you where you want to go.
In fact, your new validator could be as simple as
class SchemelessURLValidator(URLValidator):
regex = re.compile(
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
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