'getting error Authentication credentials were not provided in django rest framework
Hi Everyone i am creating login api in DRF and getting response also as i expected but i test token to other api then got error Authentication credentials were not provided, i don't know where i am going wrong please help me out.also custom user model can't possible to use because that model i have already used
setting.py- this is setting file
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'api.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication'
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'rest_framework_datatables.renderers.DatatablesRenderer',
),
'DEFAULT_FILTER_BACKENDS': (
'rest_framework_datatables.filters.DatatablesFilterBackend',
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination',
'PAGE_SIZE': 100,
}
models.py
class GmsUser(GmsBaseModel):
first_name=models.CharField(max_length=255,null=True, blank=True)
middle_name=models.CharField(max_length=255,null=True, blank=True)
last_name=models.CharField(max_length=255,null=True, blank=True)
user_name=models.CharField(max_length=255,null=True, blank=True, unique=True)
password=models.CharField(max_length=255,null=True, blank=True)
token = models.CharField(max_length=255, null=True)
class Meta:
db_table = "gms_users"
def __str__(self):
return self.user_name
views.py
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def gms_user_login(request):
user_name = request.data.get("user_name")
password = request.data.get("password")
users=GmsUser.objects.filter(user_name=user_name).values_list('id',flat=True)
role=GmsRole.objects.filter(id=GmsUserRole.objects.filter(user=users[0]).values_list('role',flat=True)[0]).values_list('role',flat=True)[0]
# city=GmsUserProfile.objects.filter(user=users[0]).values_list('city',flat=True)[0]
try:
query=GmsUserRole.objects.filter(user=users[0]).exists()
except Exception as e:
return Response({"message":"User not found","error":True,"code":400,"results":str(e)},status=HTTP_400_BAD_REQUEST)
if user_name is None or password is None:
return Response({'detail': 'Please provide both username and password'})
else:
try:
if query:
user = GmsUser.objects.get(user_name=user_name)
except GmsUser.DoesNotExist:
return Response({'detail': 'Invalid UserName'})
if user.password.lower() != password.lower():
return Response({'detail': 'Invalid Password'})
user.token=get_random_string(length=50)
user.save()
response_data=GmsUserSignupSerializer(user).data
response_data1=GmsRoleSerializer(GmsRole.objects.get(role=role)).data
response_data2=GmsUserProfileSerializer(GmsUserProfile.objects.get(user=users[0])).data
response_data['roles']=response_data1
response_data['user_profile']=response_data2
try:
return JsonResponse({"message": "login","error":False,"code":200,"results":{'token':user.token,'user':response_data}},status=HTTP_200_OK)
except Exception as e:
return JsonResponse({"message": "login","error":True,"code":500,"results":str(e)},status=HTTP_200_OK)
Login api Response
{
"message": "login",
"error": false,
"code": 200,
"results": {
"token": "7R1EAR6qQdTyM6ZvD7kHfwdCHoj33tsp1QXUCIXSqU8929uMOq",
"user": {
"id": 4,
"user_name": "edwin",
"password": "1234"
"roles": {
"id": 1
},
"user_profile": {
"id": 2
"city": 1
}
}
}
}
Solution 1:[1]
I think you need to set the right authentication
class to be used in settings.py.
Now there are 4 classes defined. But I think you have to set one class.
If you select the rest_framework.authentication.TokenAuthentication
, you don't need to create token with random string. The rest_framework.authtoken
app will create Token
model and you can just use that.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
# 'api.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework_simplejwt.authentication.JWTAuthentication'
),
...
}
Hope it could help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David Lu |