Can I make the ‘login’ field as ‘username’ field with AbstractBaseUser?
I need to have a ‘username’ property with the name ‘login’ instead of ‘username’
import jwt
from datetime import datetime, timedelta
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
from django.utils.timezone import datetime
class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError('Users must have a username.')
user = self.model(username=username)
user.set_password(password)
user.save()
return user
def create_superuser(self, username, password):
"""
Create and return a `User` with superuser (admin) permissions.
"""
if password is None:
raise TypeError('Superusers must have a password.')
user = self.create_user(username, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
login = models.CharField(db_index=True, max_length=255, unique=True)
#email = models.EmailField(db_index=True, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
# A timestamp representing when this object was created.
created_at = models.DateTimeField(auto_now_add=True)
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField(auto_now=True)
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.login
@property
def token(self):
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token().
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token()
def get_full_name(self):
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.login
def get_short_name(self):
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.login
def _generate_jwt_token(self):
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now() + timedelta(days=60)
token = jwt.encode({
'id': self.pk,
'exp': int(dt.strftime('%s'))
}, settings.SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
I have:
if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any(
File "C:\Users\Mozzarella\Envs\customFormEnv\lib\site-packages\django\db\models\options.py", line 610, in get_field
raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: User has no field named 'username'