Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django urlfield http prefix

Tags:

url

django

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://'?

like image 921
Jerry Meng Avatar asked Apr 30 '13 18:04

Jerry Meng


1 Answers

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)
like image 92
Michael C. O'Connor Avatar answered Oct 31 '22 11:10

Michael C. O'Connor