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.
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()
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',
)])
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