fabtjar
September 9, 2022, 2:52pm
1
For the URLField
it will assume http://
if one isn’t supplied. I want my field to work like this.
return list(urlsplit(url))
except ValueError:
# urlparse.urlsplit can raise a ValueError with some
# misformatted URLs.
raise ValidationError(self.error_messages["invalid"], code="invalid")
value = super().to_python(value)
if value:
url_fields = split_url(value)
if not url_fields[0]:
# If no URL scheme given, assume http://
url_fields[0] = "http"
if not url_fields[1]:
# Assume that if no domain is provided, that the path segment
# contains the domain.
url_fields[1] = url_fields[2]
url_fields[2] = ""
# Rebuild the url_fields list, since the domain segment may now
# contain the path too.
url_fields = split_url(urlunsplit(url_fields))
value = urlunsplit(url_fields)
But the URLValidator
raises an error.
if schemes is not None:
self.schemes = schemes
def __call__(self, value):
if not isinstance(value, str):
raise ValidationError(self.message, code=self.code, params={"value": value})
if self.unsafe_chars.intersection(value):
raise ValidationError(self.message, code=self.code, params={"value": value})
# Check if the scheme is valid.
scheme = value.split("://")[0].lower()
if scheme not in self.schemes:
raise ValidationError(self.message, code=self.code, params={"value": value})
# Then check full URL
try:
splitted_url = urlsplit(value)
except ValueError:
raise ValidationError(self.message, code=self.code, params={"value": value})
try:
super().__call__(value)
except ValidationError as e:
Shouldn’t the Field
validator and to_python
methods match?
It looks like I will have to create my own validator that is more relaxed. Unless someone knows a better way to handle this?
No, I don’t think they should - nor do they need to.
Those functions (to_python
and a field validator) provide two different functions with two different sets of requirements.
Note that one of the uses of to_python
is in the clean
methods of form input. You may want to accept an input of an “incomplete” url from a form as valid, to subsequently add the scheme within your code.
You can then clean-up that field before saving it to the database - which is where the Validator is used.