Skip to content
Advertisement

Make User email unique django

How can I make a Django User email unique when a user is signing up?

forms.py

JavaScript

I’m using the from django.contrib.auth.models User. Do I need to override the User in the model. Currently the model doesn’t make a reference to User.

views.py

JavaScript

Advertisement

Answer

The best answer is to use CustomUser by subclassing the AbstractUser and put the unique email address there. For example:

JavaScript

and update the settings with AUTH_USER_MODEL="app.CustomUser".

But if its not necessary for you to store the unique email in Database or maybe not use it as username field, then you can update the form’s clean method to put a validation. For example:

JavaScript

Update

If you are in mid project, then you can follow the documentation on how to change migration, in short which is to:

  1. Backup you DB
  2. Create a custom user model identical to auth.User, call it User (so many-to-many tables keep the same name) and set db_table=’auth_user’ (so it uses the same table)
  3. Delete all Migrations File(except for __init__.py)
  4. Delete all entry from table django_migrations
  5. Create all migrations file using python manage.py makemigrations
  6. Run fake migrations by python manage.py migrate --fake
  7. Unset db_table, make other changes to the custom model, generate migrations, apply them

But if you are just starting, then delete the DB and migrations files in migration directory except for __init__.py. Then create a new DB, create new set of migrations by python manage.py makemigrations and apply migrations by python manage.py migrate.

And for references in other models, you can reference them to settings.AUTH_USER_MODEL to avoid any future problems. For example:

JavaScript

It will automatically reference to the current User Model.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement