Karishma Upadhyay
Karishma Upadhyay

Reputation: 125

django token authentication not working properly

Hi Everyone i have configure token authentication in my project, when i post username and password on postman token are generating but when i added this token to access my api respose then getting [Authentication credentials were not provided.]

models.py

from rest_framework.authtoken.models import Token

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

settings.py

INSTALLED_APPS = [
'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'api.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication'
    ),
    '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,
}

urls.py

from rest_framework.authtoken.views import obtain_auth_token

router = routers.DefaultRouter()
router.register(r'api/hisaabApi',views.HisaabViewSet)
urlpatterns = [
    path('login',obtain_auth_token,name="login")
]

#api for response

views.py

class HisaabViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset=WeeklyData.objects.all()
    serializer_class=HisaabSerializer

serializers.py

class HisaabSerializer(serializers.ModelSerializer):
    class Meta:
        model = WeeklyData
        fields = '__all__'

Upvotes: 0

Views: 819

Answers (1)

🦋 Butterfly 🦋

if you are using post man you should not insert the token in params section, thats why when you are entering the Bearer and the token, it will be typed in the url at the top. enter image description here

what you should do is to enter the Bearer and the token in headers part in postman , then your code will work just fine.

enter image description here

Upvotes: 1

Related Questions