首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django Rest框架身份验证和用户会话

Django Rest框架身份验证和用户会话
EN

Stack Overflow用户
提问于 2021-09-10 18:30:22
回答 1查看 117关注 0票数 1

我正在尝试向我的django-react应用程序添加身份验证。在这一点上,我能够登录/注册用户,它的工作很好,但我只想得到的数据,与用户登录,所以张贴或更新他们。现在,我获得了所有数据,而不管哪个用户已通过身份验证。我想我必须在我的视图中改变它,但是怎么做呢?这是我的一个班级

代码语言:javascript
复制
class ListView(viewsets.ModelViewSet):
    serializer_class = ListSerializer
    
    queryset = List.objects.all()

在前端,我以这种方式获取数据:

代码语言:javascript
复制
  const getList = async () => {
    try {
    const response = await axiosInstance.get('/list/')
    if(response){
    setList(response.data)
    }
    }catch(error){
      throw error;
    }
  }
EN

回答 1

Stack Overflow用户

发布于 2021-09-10 18:34:46

您可以使用Django Rest Framework在每个视图或每个视图集的基础上设置身份验证方案。使用基于APIView类的视图:

代码语言:javascript
复制
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)

记得设置它:

代码语言:javascript
复制
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

阅读更多here

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69136605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档