suprita shankar
suprita shankar

Reputation: 1579

Unique email constraint for django.contrib.auth.user

I have changed django.contrib.auth.user model where I have made the email id to be unique. After which I added a datamigration to reflect the same-

Now when I add a user whose email is not unique, it gives me an error and does not let me create the user through the django admin. But when i do: >

How can I add an unique constraint to django.contrib.auth.user.email for an existing project (with data)?

Upvotes: 4

Views: 1329

Answers (1)

Austin Phillips
Austin Phillips

Reputation: 15766

Checks for uniqueness occur during model validation as per the Model validation documentation. Calling save() on the model doesn't automatically cause model validation. The admin application will be calling model validation.

Nothing prevents you from creating a User object in Python such as user=User('cust1','123','[email protected]') and then doing a user.save(). If there are uniqueness checks at the database level, you'll likely get an exception at this point. If you want to check before doing the save, call is_valid() on the Model instance.

If you want every User object to be automatically validated before save, use the pre_save Django signal to do Model validation before the save proceeds.

Upvotes: 1

Related Questions