Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

missing 1 required positional argument: 'pk'

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.

like image 853
lwin Avatar asked Jul 02 '19 04:07

lwin


1 Answers

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()), 
]
like image 145
Mehak Avatar answered Sep 25 '22 12:09

Mehak