Pre-requisite: model validation only happens when you call full_clean()
. If you use a ModelForm, this is done for you when you call form.save()
, but if you upload an Excel file with custom view logic, then you need to do this yourself:
There are three steps involved in validating a model:
- Validate the model fields - Model.clean_fields()
- Validate the model as a whole - Model.clean()
- Validate the field uniqueness - Model.validate_unique()
All three steps are performed when you call a model’s full_clean() method.
As I said earlier, there's no way to tell the URLField to require fully qualified URLs. For that you need to override the URLValidator.
That has a very nasty regular expression and you probably do not want to mess with that, so an alternative is to add additional validators:
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
@deconstructible
class RequireHttpOrHttpsUrl:
def __call__(self, value):
if not value.startswith("http://") and not value.startswith("https://"):
raise ValidationError('Please provide a http or https resource')
class KeyWord(models.Model):
keyword = models.CharField(verbose_name="Topic",max_length=50)
link = models.URLField(
verbose_name = "Next Best Action",
max_length=500, null=True,
validators=[RequireHttpOrHttpsUrl()]
)
def __str__(self):
return self.keyword
On using urllib.parse() as suggested in the comments:
I highly suggest playing around with URLValidator to where urllib.parse() does better. URLValidator rejects:
- http://
- http://bla
- https://bla
Accepts:
So, I can't find the upside to adding another parser.