db error,axios get方法返回(TypeError:int()参数必须是字符串,类字节对象或数字,而不是'AnonymousUser')500

问题描述 投票:0回答:2

我正在尝试获取与登录用户相关的数据列表,我正在使用vuejs,axios和drf。双面打开了corsheader。我成功获取身份验证令牌,更改状态并将其保存在本地存储中。获取用户指定数据的代码失败,这是我的代码:

views.py

class blogsListView(generics.ListAPIView):
    def get_queryset(self):
        return CodeNote.objects.filter(user=self.request.user)
    serializer_class = blogsSerializer

myblogs.vue

<script>
import axios from "axios";
const API_URL = "http://127.0.0.1:8000/";
export default {
  name: "myBlogs",
  data: () => ({
    blogs: []
  }),
  mounted() {
    let token = localStorage.getItem("TOKEN_STORAGE_KEY");
    console.log(token);
    axios
      .get(API_URL + "blogs/mylist", {
        headers: { Authorization: "Token " + token }
      })
      .then(response => {
        this.blogs = response;
      })
      .catch(e => {
        this.errors.push(e);
      });
  }
};
</script>

控制台成功显示令牌。我不确定我是否正在做正确的请求,或问题是过滤。

vue.js django-rest-framework axios token
2个回答
2
投票

您需要做的检查很少。

  • 检查是否在REST Framework设置中添加了“默认身份验证”类。实施您想拥有的任何一个。
 REST_FRAMEWORK = {
                'DEFAULT_AUTHENTICATION_CLASSES':(
                    'rest_framework.authentication.BasicAuthentication',
                    'rest_framework.authentication.SessionAuthentication',
                    'rest_framework.authentication.TokenAuthentication',
                )
    }
  • 在您的视图中您必须添加permission_classes。如果要仅提供对经过身份验证的用户的访问权限。
  class blogsListView(generics.ListAPIView):
        queryset = CodeNote.objects.all()
        serializer_class = blogsSerializer
        permission_classes = [IsAuthenticated
  • 如果您想要提供对经过身份验证的用户和普通用户的访问权限。您必须检查用户是否经过身份验证并进行相应处理。
 def get_queryset(self):
     if self.request.user.is_authenticated:
        return CodeNote.objects.filter(user=self.request.user)
     return []
  • 检查从前端发送本地存储的令牌是否实际存在于数据库中。
  • 一体
    class blogsListView(generics.ListAPIView):
        queryset = CodeNote.objects.all()
        serializer_class = blogsSerializer
        # permission_classes = [IsAuthenticated]

        def get_queryset(self):
            if self.request.user.is_authenticated:
                return CodeNote.objects.filter(user=self.request.user)
            return []

0
投票

它成功了,谢谢@bkwan的帮助,我添加了休息框架设置,并编辑了这样的axios请求:

 REST_FRAMEWORK = {
                'DEFAULT_AUTHENTICATION_CLASSES':(
                    'rest_framework.authentication.BasicAuthentication',
                    'rest_framework.authentication.SessionAuthentication',
                    'rest_framework.authentication.TokenAuthentication',
                )
    }
 def get_queryset(self):
     if self.request.user.is_authenticated:
        return CodeNote.objects.filter(user=self.request.user)
     return []
axios
      .get(API_URL + "blogs/mylist", {
        headers: { Authorization: `Token ${token}` }
      })

© www.soinside.com 2019 - 2024. All rights reserved.