Django how to make user model username unique=False

713 views
Skip to first unread message

chern...@gmail.com

unread,
Jan 9, 2018, 3:39:32 AM1/9/18
to Django users
I am trying to make username unique = false as there are cases where username is not needed. Since i am using email address to login.
But with the django user model, how do i customise it ? 

Here is the code for my current user model:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import UserManager
from django.db.models import Q
from django.core.validators import RegexValidator


class CustomUserManager(UserManager):

def get_by_natural_key(self, username):
return self.get(
# this comment is to prevent user from using username to login
# Q(**{self.model.USERNAME_FIELD: username}) |
Q(**{self.model.EMAIL_FIELD: username})
)


class MyUser(AbstractUser):
userId = models.AutoField(primary_key=True)
gender = models.CharField(max_length=6, blank=True, null=True)
nric = models.CharField(max_length=40, blank=True, null=True)
birthday = models.DateField(blank=True, null=True)
birthTime = models.TimeField(blank=True, null=True)
ethnicGroup = models.CharField(max_length=30, blank=True, null=True)
favoriteClinic = models.CharField(max_length=50, blank=True, null=True)
appVer = models.CharField(max_length=50, blank=True, null=True)
osVer = models.CharField(max_length=50, blank=True, null=True)
mobileType = models.IntegerField(blank=True, null=True)
country_code = models.IntegerField(blank=True, null=True)
# mobile_regex = RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}$', message="Phone number must not consist of space and requires country code. eg : +6591258565")
mobileNo = models.CharField(max_length=25, blank=True, null=True) # validators should be a list
height = models.FloatField(blank=True, null=True)
weight = models.FloatField(blank=True, null=True)
bloodtype = models.CharField(max_length=3, blank=True, null=True)
allergy = models.CharField(max_length=30, blank=True, null=True)
# image1 = models.ImageField(upload_to=)
# image = models.BinaryField(editable=True, blank=True, null=True)
# displaypicture = models.ImageField
objects = CustomUserManager()

def __str__(self):
return self.username

Andréas Kühne

unread,
Jan 9, 2018, 4:18:20 AM1/9/18
to django...@googlegroups.com
Hi,

This is how I created my User model that does what you require:

class User(AbstractBaseUser, PermissionsMixin, AuditableModel):
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('email address'), blank=False, null=False, unique=True)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
objects = CustomUserManager()

EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

def clean(self):
"""
Override the default clean method to include normalization of the email field.
"""
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)

def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between if set, otherwise the email address.
"""
full_name = f'{self.first_name} {self.last_name}'.strip()

if not full_name:
full_name = self.email

return full_name

def get_short_name(self):
"Returns the short name for the user."
return self.first_name

class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')

The reason for the CustomUserManager is to override some methods when creating users.

By setting the USERNAME_FIELD to 'email' you can remove the CustomUserManager that you have declared (which by the way I don't think will work). You can check here for more information about creating your own user model with email as username field:

Here you can also see the CustomUserManager that will be required. :-)

Regards,

Andréas

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/81ce75ad-bada-4975-8dbc-df41de40b392%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

chern...@gmail.com

unread,
Jan 9, 2018, 8:41:44 PM1/9/18
to Django users
Thanks for these improvement. But the main thing i want is to make username field unique = false

chern...@gmail.com

unread,
Jan 9, 2018, 9:57:17 PM1/9/18
to Django users
The reason is because i want to add some user without entering their username. As i manage to allow null input for username but the unique for username make it an error if i add another user without username. These user are used for adding family member. For eg creating a 3 years old baby profile as family member.
Reply all
Reply to author
Forward
0 new messages