无法在 Django REST+React 框架中执行 axios PUT 请求 - 错误 403

IT技术 django reactjs django-rest-framework axios
2021-05-03 05:30:44

我可以通过以下方式进行 GET 请求:

axios.get('/by/f')
        .then(function (data) {
            this.setState({list: data.data});
        }.bind(this))
        .catch(function (error) {
            console.log(error);
        });

但是,当我尝试 PUT 请求来更新我的 django 数据库时,出现 403 错误:

axios({
        method: 'put',
        url: '/by/f',
        data: {
            item: item,
            frequency: frequency
        }
    }).then(function (response) {
        console.log(response);
    });

我的观点:

class FrequencyList(APIView):
def get(self, request, format=None):
    frequency = Frequency.objects.all()
    serializer = FrequencySerializer(frequency, many=True)
    return Response(serializer.data)

def put(self, request, pk, format=None):
    frequency = self.get_object(pk)
    serializer = FrequencySerializer(frequency, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我的网址模式:

urlpatterns = [
    path('f', views.FrequencyList.as_view()),
]

我的标题:

headers: {
  'Access-Control-Allow-Origin': '*'
},
1个回答

您的 FrequencyList 视图适用于获取所有频率列表和添加新频率。换句话说,get 和 post 请求适用于 FrequencyList 视图。但是您不能对详细信息 api(update/delete/getDeatails) 使用相同的视图。对于这些操作,您需要频率的 id。所以对于更新(放置函数)创建新的 api/view。

网址.py

urlpatterns = [
    path('f', views.FrequencyList.as_view()),
    path('f/(?P<pk>[0-9]+)$', views.FrequencyDetail.as_view()),

视图.py

class FrequencyList(APIView):
    def get(self, request, format=None):
        frequency = Frequency.objects.all()
        serializer = FrequencySerializer(frequency, many=True)
        return Response(serializer.data)

class FrequencyDetail(APIView)
    def put(self, request, pk, format=None):
        frequency = Frequency.objects.get(id=pk)
        serializer = FrequencySerializer(frequency, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

你的脚本应该是

axios({
        method: 'put',
        url: '/by/f/' + frequency, # hope frequency is the id of the object that you want to update
        data: {
            item: item,
        }
    }).then(function (response) {
        console.log(response);
    });

并且在 get 中没有变化

axios.get('/by/f')
        .then(function (data) {
            this.setState({list: data.data});
        }.bind(this))
        .catch(function (error) {
            console.log(error);
        });

更新

frequency = Frequency.objects.get(id=pk) 如果你想处理找不到对象的错误,可以用下面的代码替换

queryset = Frequency.objects.all()
frequency = get_object_or_404(queryset, pk=pk) # from django.shortcuts import get_object_or_404