我试图添加身份验证到我的django-react应用程序。在这一点上,我能够登录/注册用户,它的工作很好,但我想只得到与用户登录相关的数据,所以张贴或更新他们。现在我得到了所有的数据,不管用户是谁。我想我必须改变我的观点,但怎么做呢?这是我的一个类
class ListView(viewsets.ModelViewSet):
serializer_class = ListSerializer
queryset = List.objects.all()
在前端,我这样获取数据:
const getList = async () => {
try {
const response = await axiosInstance.get('/list/')
if(response){
setList(response.data)
}
}catch(error){
throw error;
}
}
你可以使用Django Rest框架在每个视图或每个视图集的基础上设置认证方案。使用基于APIView类的视图:
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)
记得设置:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
点击这里阅读更多