[Answered ]-How to Validate Against Current User in Django?

1👍

You can make it slightly more efficient by cleaning this with the primary key of the referred_by, since that avoids an extra query. Furthermore you should call the super().clean() such that validations on parent class(es) are also performed, and you can also try to enforce this at the database side with Django’s constraint framework [Django-doc]:

from django.core.exceptions import ValidationError
from django.db.models import F, Q

class User(AbstractBaseUser, PermissionsMixin):
    # …
    
    def clean(self, *args, **kwargs):
        if self.pk == self.referred_by_id:
            raise ValidationError('Can not refer to itself!')
        return super().clean(*args, **kwargs)

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=~Q(pk=F('referred_by_id')),
                name='age_gte_18'
            )
        ]

Leave a comment