缺少 1 个必需的位置参数:'pk' [英] missing 1 required positional argument: 'pk'

查看:20
本文介绍了缺少 1 个必需的位置参数:'pk'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的网址=>

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

这是来自 React axios 的 url 请求 =>

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

我可以执行 get 和 post 方法,但由于此错误,不能执行 put 和 delete 方法.我设置了 pk 键,为什么它仍然发生错误?谢谢.

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.

推荐答案

发生错误是因为您在 put 方法中将 pk 作为 param 传递.

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

def put(self,request,pk):

相反,使用这个:

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

为了从传递的 URL 获取 pk,请使用:

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()), 
]

这篇关于缺少 1 个必需的位置参数:'pk'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆