Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding URLField's validation with custom validation

How can I override django's URLField's validation with a custom validation? And where should this be done?

I want it to accept urls without a domain ending too.

like image 624
Capuchin Avatar asked Mar 12 '14 10:03

Capuchin


2 Answers

This is Django's Url Field Validator. Provide your custom regular expression myregex to it. However, you need to prevent the UrlField default validation, since this is not want you want.

So create your custom field like that: Then for your model / form, provide this to the field like that:

from django.forms import UrlField as DefaultUrlField
class UrlField(DefaultUrlField):
    default_validators = [URLValidator(regex=myregex)]

And then in your Form just do:

my_url_field = UrlField()
like image 65
schacki Avatar answered Nov 15 '22 20:11

schacki


You can create custom regex validation or can use Django URL Validation on your models:

Option1:

from django.core.validators import RegexValidator
URL_VALIDATOR_MESSAGE = 'Not a valid URL.'
URL_VALIDATOR = RegexValidator(regex='/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/', message=URL_VALIDATOR_MESSAGE)


class SocialAccounts(models.Model):
    user = models.ForeignKey("Profile", on_delete=models.CASCADE, blank=True, null=True, unique=True)
    facebook = models.URLField(max_length=200, null=True, blank=True, validators=[URL_VALIDATOR])

Option2:

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)


class SocialAccounts(models.Model):
    user = models.ForeignKey("Profile", on_delete=models.CASCADE, blank=True, null=True, unique=True)
    facebook = models.URLField(max_length=200, null=True, blank=True, validators=[OptionalSchemeURLValidator])
    instagram = models.URLField(max_length=200, null=True, blank=True,
                                validators=
                                    [RegexValidator(
                                        regex= '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/',
                                        message='Not a valid URL',
                                    )])
like image 2
Burak Ibis Avatar answered Nov 15 '22 21:11

Burak Ibis