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:
https://www.fomfus.com/articles/how-to-use-email-as-username-for-django-authentication-removing-the-username

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

Regards,

Andréas

2018-01-09 9:39 GMT+01:00 <[email protected]>:

> 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 <+65%209125%208565>")
>     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 [email protected].
> To post to this group, send email to [email protected].
> 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
> <https://groups.google.com/d/msgid/django-users/81ce75ad-bada-4975-8dbc-df41de40b392%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
> 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 [email protected].
To post to this group, send email to [email protected].
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 via email to