4

I have seen many of the solution but none of it seems to be answering the question.

My user model is using AbstractUser right now. Is there a way to make username(unique = False)

Since i wanted to allow user to ba able to have duplication of same username, as the login im am using is by email address and password

Below is the code that i tried but doesnt work.

Code:

class MyUser(AbstractUser):
    username = models.CharField(max_length=30, unique=False)

error:

customuser.MyUser: (auth.E003) 'MyUser.username' must be unique because it is named as the 'USERNAME_FI ELD'

Mehrdad Pedramfar
  • 9,989
  • 4
  • 33
  • 55
Jin Nii Sama
  • 627
  • 1
  • 16
  • 32

3 Answers3

2

Try to specify email as username field with USERNAME_FIELD attribute:

class MyUser(AbstractUser):
    username = models.CharField(max_length=30, unique=False)
    USERNAME_FIELD = 'email'
neverwalkaloner
  • 42,539
  • 6
  • 72
  • 87
2
class MyUser(AbstractUser):
    username = models.CharField(max_length=30, unique=False)
    email = models.EmailField(max_length=255, unique=True)
    USERNAME_FIELD = 'email'
Nikhil Bhardwaj
  • 482
  • 9
  • 16
  • Please explain a little about your answer. – Mehrdad Pedramfar Feb 16 '19 at 07:45
  • @MehrdadPedramfar I don't know about his code so I just want give some info related to his code and I don't want to add something additional in it..... And he is inheriting AbstractUser class so, that username field will directly make an impact on the Django username field.... This is it – Nikhil Bhardwaj Feb 16 '19 at 10:45
2

A non-unique username field is allowed if you use a custom authentication backend that can support it.

If you want to use django's default authentication backend you cannot make username non unique.

You will have to implement a class with get_user(user_id) and authenticate(request, **credentials) methods for a custom backend.

You can read it in the documentation here. https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#specifying-custom-user-model

himank
  • 419
  • 3
  • 5