缺少1个必需的位置参数:“ pk”

时间:2019-07-02 04:00:20

标签: django reactjs django-rest-framework axios

我是Django的新手,会做出反应。上周我已经遇到了这个错误,那一次是请求URL错误。昨天我更改了后端设计,现在它的错误再次发生。

这是我的网址=>

urlpatterns = [
    url(r'^allowances_mas/', AllowanceAPIView.as_view()),
    url(r'^allowances_mas/(?P<pk>\d+)/$', AllowanceAPIView.as_view()),....

这是我在视图内部的put方法,

def put(self,request,pk):
        save_allowance = get_object_or_404(Allowance.objects.all(),pk=pk)
        data = request.data.get('allowance')
        serializer = AllowanceSerializer(instance=save_allowance,data=data,partial=True)

        if serializer.is_valid():           
            allowance_saved=serializer.save()
            return Response({"success":"Allowance '{}' updated successfully".format(allowance_saved.AllowID)})
        else:
            return Response({"fail":"'{}'".format(serializer.errors)})  

这是来自React axios的网址请求=>

  axios.put('http://127.0.0.1:8000/api/allowances_mas/1/', { allowance },{
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => {
          axios.get('http://127.0.0.1:8000/api/allowances_mas/')
          .then(res=>{
            const resallowance=res.data.allowance;  

            this.setState({
              allowances:resallowance 
            });
          })      
        })
        .catch(err=>{
          console.log("error",err);
        })
        .finally(fin=>{
          console.log(fin);
        })

我可以执行get和post方法,但是由于此错误,不能放置和删除。我设置了pk键,为什么它仍然会发生错误?谢谢。

1 个答案:

答案 0 :(得分:1)

发生错误是因为在put方法中将pk作为参数传递。

def put(self,request,pk):

相反,请使用:

def put(self, request, *args, **kwargs):

要从传递的网址中获取pk,请使用以下代码:

pk = self.kwargs.get('pk')

因此您的代码应如下所示:

def put(self,request, *args, **kwargs):
    pk = self.kwargs.get('pk')
    save_allowance = get_object_or_404(Allowance.objects.all(), pk=pk)
    data = request.data.get('allowance')
    serializer = AllowanceSerializer(instance=save_allowance,data=data,partial=True)

    if serializer.is_valid():           
        allowance_saved=serializer.save()
        return Response({"success":"Allowance '{}' updated successfully".format(allowance_saved.AllowID)})
    else:
        return Response({"fail":"'{}'".format(serializer.errors)})  

此外,更改网址格式的顺序:

urlpatterns = [
    url(r'^allowances_mas/(?P<pk>\d+)/$', AllowanceAPIView.as_view()),
    url(r'^allowances_mas/', AllowanceAPIView.as_view()), 
]