10

I am trying to use the email field in the default Django user model as the username. I am using Django 1.5 and I saw that the default user has a USERNAME_FIELD property.

In my project, I would like to set the following USERNAME_FIELD = 'email' as a default in the user model.

This small but fundamental tweak is the only thing I would like to change in the user model. I was wondering if there is a way of changing the USERNAME_FIELD without having to subclass the AbstractUser. I saw in this question that you can subclass the AbstractUser and write a custom manager for it.

So I was wondering if there is a simpler way of changing that property?

And if not, what would be the minimal way of extending the AbstractUser to use the email field as username?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
yellowcap
  • 3,985
  • 38
  • 51
  • use AbstraceBaseUser instead – catherine Mar 28 '13 at 02:00
  • @catherine If you Subclass AbstractUser you end up in these problems:http://stackoverflow.com/questions/16605453/django-1-5-extend-the-default-user-model-or-substitute-it and http://stackoverflow.com/questions/16601412/upgrading-django-to-1-5-with-django-cms-user-model-issue – Daviddd May 17 '13 at 09:39

2 Answers2

4
#Your app's __init__.py

from django.contrib.auth.models import User

User.USERNAME_FIELD = 'email'
Thomas
  • 11,757
  • 4
  • 41
  • 57
  • 7
    This raises the error "django.core.management.base.CommandError: One or more models did not validate: auth.user: The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model. auth.user: The USERNAME_FIELD must be unique. Add unique=True to the field parameters." for me. – Martey May 30 '13 at 18:35
  • 1
    Same problem with me... I wonder if there have been any changes that break this between Mar '13 and May '13 or so. I would have really liked for this to work.. – user1496984 Mar 01 '15 at 18:24
1

You have to write a new Custom User Class by extending the AbstractBaseUser and not AbstractUser

Declare your email as the USERNAME_FIELD there

Optionally you can also declare a custom user manager that extends from BaseUserManager to handle the username required constraint. You can remove username from that manager's create_user function

Snigdha Batra
  • 867
  • 8
  • 16