Skip to content Skip to sidebar Skip to footer

Django Rest Framework Validation Error: 'enter A Valid Url.'

In my Django REST Framework project, I have a model class for saving services that the Django app will crawl in a background task: class Service(models.Model): name = models.Ch

Solution 1:

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....")

classFooModel(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

classOptionalSchemeURLValidator(URLValidator):def__call__(self, value):
        if'://'notinvalue:# Validate as if it were http://
            value = 'http://' + value
        super(OptionalSchemeURLValidator, self).__call__(value)

classFooModel(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

Post a Comment for "Django Rest Framework Validation Error: 'enter A Valid Url.'"