missing 1 required positional argument: 'pk'

不打扰是莪最后的温柔 提交于 2020-04-11 06:46:08

问题


I am new in Django and react. I already faced this error at last week and That times its was request URL error. yesterday I changed backend design and now its error happens again.

Here is my url=>

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

here is my put method that inside view,

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)})  

Here is url request from 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);
        })

I can do get and post method but put and delete can't because of this error. I set the pk key and why it's still happening the error? Thanks.


回答1:


The error occurs because you're passing pk as param in put method.

def put(self,request,pk):

Instead, use this:

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

And for fetching pk from passed URL, use this:

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

So your code should look like this:

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)})  

Also, change the order of URL patterns:

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


来源:https://stackoverflow.com/questions/56845135/missing-1-required-positional-argument-pk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!