我正在尝试向我的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;
}
}发布于 2021-09-10 18:34:46
您可以使用Django Rest Framework在每个视图或每个视图集的基础上设置身份验证方案。使用基于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',
]
}阅读更多here
https://stackoverflow.com/questions/69136605
复制相似问题