Adding unique together errors to one of the involved fields

I’m building an application with multi-tenancy, meaning that all data is associated to a tenant model. When creating models, I often want to validate uniqueness of e.g. the name field. However, the uniqueness is only required per tenant, not globally, which is why I’m using unique_together (or UniqueConstraint, found that too late, but will migrate).

However, when the uniqueness is violated, a non_field_error is added. I would however prefer to add this error to the name field, as the tenant field is implicit and not visible to the user (the tenant is always the tenant of the logged in user, and can’t be chosen).

Any hints on how I could achieve that, preferably in the model or alternatively in a form? I thought about first validating the model, and then moving the error from the non_field_errors to the name field, but that feels kind of wrong.

Starting point would be this code:

class Company(models.Model):
    tenant = models.ForeignKey(Tenant, on_delete=models.PROTECT)
    name = models.CharField(max_length=255)

    class Meta:
        unique_together = ('tenant', 'name')

Thanks in advance :slight_smile: