Reputation: 89
I'm trying to add authentication to my django-react app. At this point I am able to login/register users and it works fine but I want to get only data which is related with user logged in so posted or updated by them. Now I get all data regardless of user which is authenticated. I assume I have to change it in my views but how to do this? This is one of my classes
class ListView(viewsets.ModelViewSet):
serializer_class = ListSerializer
queryset = List.objects.all()
And on frontend side I get data this way:
const getList = async () => {
try {
const response = await axiosInstance.get('/list/')
if(response){
setList(response.data)
}
}catch(error){
throw error;
}
}
Upvotes: 1
Views: 1068
Reputation: 1382
You can use Django Rest Framework to set the authentication scheme on a per-view or per-viewset basis. Using the APIView class-based views:
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
Remember to set it up:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
Read more here
Upvotes: 1