I have a Vue front end and Django backend
I am using a custom user model:
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
today = timezone.now()
class UserManager(BaseUserManager):
def create_user(self, email, password, username=None, role=None):
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.created_at = today
user.save()
return user
def create_superuser(self, email, password, role, username=None):
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.role = role
user.is_staff = True
user.is_active = True
user.is_superuser = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
EM = 'EM'
SM = 'SM'
DH = 'DH'
ROLES = [
(EM, 'Executive Management'),
(SM, 'Senior Management'),
(DH, 'Department Head'),
]
objects = UserManager()
role = models.CharField(max_length=2, choices=ROLES, default=US, blank=True)
username = models.CharField(max_length=100, unique=True, blank=True, null=True)
email = models.EmailField(max_length=255, unique=True)
slug = models.SlugField()
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
email_verified_at = models.DateTimeField(auto_now=False, null=True, blank=True)
confirmed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at")
class Meta:
verbose_name = "User"
verbose_name_plural = "Users"
ordering = ["username"]
db_table = "users"
def get_absolute_url(self):
return f"{self.slug}"
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['role']
I am trying to get an authentication token but the response I get is username is required. Why is it required if I set the username field to email?
I am using this code top get the token:
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email
})