Django Authentication with just an email and password (no username required!)

Ramy Khuffash
2 min readMay 31, 2016

--

Django comes with a lot of stuff out of the box, which is why I love using it. The default authentication flow requires people to pick a unique username when they sign up, which can be pointless for some types of sites.

If I’m working on a Django project where social auth makes no sense, I use a custom user model to make sure people can register with nothing more than an email and password. It must be a common use-case for custom user models, because it’s mentioned in the docs here.

I forget how to do it almost every time & tend to run into the same pitfalls (for example, creating superusers), so I’m writing this as a resource for my future self and for others who are trying to use an email address instead of username for auth. I’m hoping my process is wrong as it seems convoluted, so please correct me if there are better ways of achieving the same thing.

You need to follow this process before you do your first migration for a project. This process will only work for a new project.

  • In the models.py file for your app, add a custom user manager that deals with creating a user while treating the email as the unique identifier, instead of the username like so:
  • This custom user manager is needed because the user model isn’t what’s normally used. Here’s the code for our custom user model in the same models.py file:

This is essentially the same as the default User model for Django, except “USERNAME_FIELD” is set to ‘email’ and some of the fields are removed.

You can also add extra fields to your custom user model, but the recommendation is to add any extras through a relation to a different model.

  • Then finally in your settings.py file, you want to add:
 AUTH_USER_MODEL = ‘your_app_name.User’

From this point on instead of referencing the user model with User, you should use either “settings.AUTH_USER_MODEL” or “get_user_model()”. You can learn when to use either here.

At this point, you should be able to run manage.py makemigrations then manage.py migrate and auth should work fine without requiring a username.

Hopefully that went smoothly for you. You should check out the official docs for more information.

Please let me know if you have any questions and I’ll do my best to help.

--

--