2

I'm trying to create a rest api using an existing database. I am also using drf token authentication and have created tokens for all existing users. When I try to enter my username and password to get my token from my ObtainAuthToken View I receive the following error:

 "non_field_errors": [
        "Unable to log in with provided credentials."
    ]

My code is as follows:

Views.py

from django.shortcuts import render
from django.db import connection
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework import filters
from rest_framework import generics
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer

from api import serializers
from api import  models

from itertools import chain
# Create your views here.

class UserLoginApiView(ObtainAuthToken):
   """Handle creating user authentication tokens"""
   renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES

urls.py

from django.urls import path, include
from rest_framework.routers import DefaultRouter, SimpleRouter
from api import views

urlpatterns = [

    path('login', views.UserLoginApiView.as_view()),
    
]

models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager, UserManager
from django.conf import settings
from django.dispatch import receiver
from django.urls import reverse

class UserProfileManager(BaseUserManager):
 

    def create_user(self, email, username, password=None):
        
        if not email:
            raise ValueError('User must have an email address')

        email = self.normalize_email(email)
        user = self.model(email=email, username=username)

        user.set_password(password)
        user.save(using=self._db)

        return user


    def create_superuser(self, email, username, password):
       
        user = self.create_user(email, username, password)

        user.is_superuser = True
        user.is_staff = True
        user.save(using=self._db)

        return user


def myoverridenmeta(name, bases, adict):
    newClass = type(name, bases, adict)
    for field in newClass._meta.fields:
        if field.attname == 'last_login':
            field.column = 'lastLogin'
            field.db_column = 'lastLogin'
    return newClass


class InvshellUsers(AbstractBaseUser, PermissionsMixin):
    id = models.AutoField(db_column='userID', primary_key=True)  # Field name made lowercase.
    username = models.CharField(max_length=20,unique=True)
    password = models.CharField(max_length=50)
    first_name = models.CharField(db_column='firstName', max_length=50, blank=True, null=True)  # Field name made lowercase.
    lastname = models.CharField(db_column='lastName', max_length=50, blank=True, null=True)  # Field name made lowercase.
    email = models.CharField(max_length=50, blank=True, unique = True, null=True)
    orgid = models.IntegerField(db_column='orgID', blank=True, null=True)  # Field name made lowercase.
    territoryid = models.IntegerField(db_column='territoryID', blank=True, null=True)  # Field name made lowercase.
    locationid = models.IntegerField(db_column='locationID', blank=True, null=True)  # Field name made lowercase.
    role = models.CharField(max_length=15, blank=True, null=True)
    status = models.CharField(max_length=15, blank=True, null=True)
    timezone = models.CharField(max_length=50, blank=True, null=True)
    last_login = models.DateTimeField(db_column='lastLogin', blank=True, null=True)  # Field name made lowercase.
    loginattempts = models.IntegerField(db_column='loginAttempts', blank=True, null=True)  # Field name made lowercase.
    passchangedate = models.DateTimeField(db_column='passChangeDate', blank=True, null=True)  # Field name made lowercase.
    activatedate = models.DateTimeField(db_column='activateDate', blank=True, null=True)  # Field name made lowercase.
    addedby = models.CharField(db_column='addedBy', max_length=50, blank=True, null=True)  # Field name made lowercase.
    uom = models.IntegerField(blank=True, null=True)
    uomtemp = models.IntegerField(db_column='uomTemp', blank=True, null=True)  # Field name made lowercase.

    objects = UserProfileManager()
    
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def get_short_name(self):
        return self.username

    def __str__(self):
        
        return self.email
    
    __metaclass__ = myoverridenmeta
    class Meta:
        managed = True
        db_table = 'invShell_users'

Relavent info from settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'push_notifications',
    #'django_celery_beat',
    'api',
]

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
}

AUTH_USER_MODEL='api.InvshellUsers'

Any help figuring out this error is much appreciated

TJ D'Alessandro
  • 109
  • 1
  • 19
  • 1
    Does any of these answers help? https://stackoverflow.com/questions/40076254/drf-auth-token-non-field-errors-unable-to-log-in-with-provided-credential – Shradha Jan 15 '21 at 18:47
  • The message suggests that either the username or password are incorrect. Or perhaps the user is not active. Have you checked their `is_active` is `True`? – tim-mccurrach Jan 17 '21 at 23:01
  • @tim-mccurrach I had a problem like this once and that was the case - the password was being set incorrectly. perhaps look into that – twrought Jan 22 '21 at 01:50
  • @jeanmw Could you add the full traceback of your error? – Yevgeniy Kosmak Dec 22 '21 at 22:17

0 Answers0