Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django custom user model with unique_together on the email

Tags:

python

django

I'm trying to create a custom User model in my Django app, the problem is I get an error saying email must be unique (fair enough!), however, I need email and company together to be unique, as I may have the same email but registered to a different company.

I get the following error:

ERRORS:
site.SiteUser: (auth.E003) 'SiteUser.email' must be unique because it is named as the 'USERNAME_FIELD'.

Here is my model:

class SiteUser(models.Model):
    company = models.ForeignKey(Company)
    email = models.EmailField(max_length=254)

    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(auto_now=False, auto_now_add=True)

    objects = SiteUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        unique_together = ('company', 'email',)
like image 692
Munro Avatar asked Dec 08 '22 04:12

Munro


2 Answers

You're missing the unique=True in your email field definition. The filed that is used in the USERNAME_FIELD should have this argument as explained in the django doc on USERNAME_FIELD.

It should be like this:

email = models.EmailField(max_length=254, unique=True)
like image 71
Jonatan Vianna Avatar answered Dec 11 '22 09:12

Jonatan Vianna


Add auth.E003 to the SILENCED_SYSTEM_CHECKS setting. This will allow manage.py to run. And I think you should add W004 warning to this list too:

SILENCED_SYSTEM_CHECKS = ['auth.E003', 'auth.W004']
like image 26
catavaran Avatar answered Dec 11 '22 08:12

catavaran