I've created a custom validation function for my model in Django as following:
class Profile(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
primary_key=True,
default=None
)
company_name = models.CharField(validators=[validate_url],max_length=50, null=False, blank=False)
...
My validate_url function converts the company_name into an url and checks if the same generated url already exist in any profiles.
def validate_url(value):
url = value.replace(' ', '-')
url = url.lower()
try:
u = Profile.objects.get(url=url)
raise ValidationError(
'The company name already exist'
)
except Profile.DoesNotExist:
pass
This seems to work fine when new profiles are created and saved to the database. However when I'm just editing another fields of an existing profile (through admin), it raises me the validation error from the validate_url because it sees himself as already existent value. I would want to pass the user of that instance and check if that user is equal to u.user from u = Profile.objects.get(url=url) and if they are equal it should not raise the error.
The problems is that I cannot simply do that:
validators=[validate_url(self.user)]
Because it gives me the error that self is not defined. How can I pass the user object instance when validating before saving the profile?