8
If you have your own regex, why not just use a models.CharField instead of URLField? Like:
models.py
phone_regex = RegexValidator(
regex=r'^\+?(?:\(?[0-9]\)?\x20?){4,14}[0-9]$',
message="Error....")
class FooModel(models.Model):
phone = models.CharField("Phone Number", validators=[
phone_regex], max_length=26, blank=True, null=True)
BTW, to customize URLValidator accept urls without ‘http/https’ I use below
models.py
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)
class FooModel(models.Model):
website = models.CharField(max_length=200, validators=[OptionalSchemeURLValidator()])
This doesn’t change the uploaded value, just make the validation pass.
I tried on my DRF, it works.
refer to Alasdair’s answer, thanks Alasdair
Source:stackexchange.com