Django how to make user model username unique=False

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Django how to make user model username unique=False

cherngyorng
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

--
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 [hidden email].
To post to this group, send email to [hidden email].
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.
Reply | Threaded
Open this post in threaded view
|

Re: Django how to make user model username unique=False

Andréas Kühne
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

2018-01-09 9:39 GMT+01:00 <[hidden email]>:
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 : <a href="tel:+65%209125%208565" value="+6591258565" target="_blank">+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

--
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 [hidden email].
To post to this group, send email to [hidden email].
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.

--
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 [hidden email].
To post to this group, send email to [hidden email].
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/CAK4qSCdB3%2BTvX8LjT2i_HVYQjLpSdePuVthS5A%2BSOmRUnqxSXA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|

Re: Django how to make user model username unique=False

cherngyorng
In reply to this post by cherngyorng
Thanks for these improvement. But the main thing i want is to make username field unique = false

On Tuesday, January 9, 2018 at 5:39:32 PM UTC+9, [hidden email] wrote:
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

--
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 [hidden email].
To post to this group, send email to [hidden email].
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/1b1ca8d0-18cb-4d51-908e-9be551cdb8b9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|

Re: Django how to make user model username unique=False

cherngyorng
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.

On Wednesday, January 10, 2018 at 10:41:44 AM UTC+9, [hidden email] wrote:
Thanks for these improvement. But the main thing i want is to make username field unique = false

On Tuesday, January 9, 2018 at 5:39:32 PM UTC+9, [hidden email] wrote:
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

--
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 [hidden email].
To post to this group, send email to [hidden email].
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/64c1269c-240b-4d65-8bab-0ee19a353b4c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.