When I request this, everything is ok and I get the data:
const get_players = async()=>{
const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/')
const data = await response.json()
console.log(data)
}
But when I put permission_classes in views.py, I recive this in the console:
{detail: 'Authentication credentials were not provided.}
I am a beginner in Javascript so I wll hope you can understand.
I dont know how to put the authentication credentials in my fech.
Views.py
class PlayersView(ModelViewSet):
permission_classes = [IsAuthenticated]
serializer_class = PlayersSerializer
queryset = Players.objects.all()
def list(self, request):
queryset = Players.objects.all()
serializer = PlayersSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = Players.objects.all()
qs = get_object_or_404(queryset, pk=pk)
serializer = PlayersSerializer(qs)
return Response(serializer.data)
Urls.py
router = DefaultRouter()
router.register('players',views.PlayersView,basename='players')
app_name = 'main'
urlpatterns = [
path('',include(router.urls)),
]
Any idea?
>Solution :
The user behind the browser that runs the fetch needs to be authenticated, ie. logged in. There are multiple ways to do it. Refer to:
https://www.django-rest-framework.org/api-guide/authentication/
But basically, SessionAuthentication will use Django’s user login system, and if you want access the API without logging in, you can use TokenAuthentication in which case, you need to add an HTTP header to your fetch request.
const get_players = async() =>{
const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/', {
headers: {
'Authorization': `Token ${apiToken}`
}
})
const data = await response.json()
console.log(data)
}