gpt4 book ai didi

python - Django 1.11 get() 缺少 1 个必需的位置参数 : 'pk'

转载 作者:行者123 更新时间:2023-12-01 01:15:54 25 4
gpt4 key购买 nike

我使用的是 Django 1.11,但我遇到了路径参数问题。对于涉及路径参数的所有请求,我都会收到这样的错误。

Error:
TypeError at /posts/2
get() missing 1 required positional argument: 'pk'

urls.py
...
url(r'^posts',PostView.as_view()),
url(r'^posts/<int:pk>/',PostView.as_view()),
...

views.py
..
#-------- API for CRUD -----------------#
class PostView(APIView):
permission_classes = (IsAuthenticated,)

def get_object(self,pk,user_id):
try:
return Post.objects.get(pk=pk,user_id=user_id)
except Post.DoesNotExist:
raise Http404

def get(self,request,pk):
post = Post.objects.get(user=request.user.id)
serializer = PostSerializer(post)
return Response({"success":True,"data":serializer.data},status=status.HTTP_200_OK)

def put(self, request, pk):
post = self.get_object(pk,request.user.id)
serializer = PostSerializer(post, data=request.data)
if serializer.is_valid():
serializer.save(user=request.user.id)
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def post(self,request):
params = request.data
params['user'] = request.user.id
serializer = PostSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
saved_data = self.perform_create(serializer)
post = PostSerializer(saved_data)
return Response({"success":True, "message":"Post Added Successfully","data":post.data}, status=status.HTTP_201_CREATED)

def perform_create(self, serializer):
return serializer.save()
...

网址示例:

GET : localhost:8000/posts/2

有人可以告诉我如何传递位置参数吗?

最佳答案

在上面的代码中,您使用 user_idpk 作为请求方法和 View 方法 get_object 中的位置参数。 pkuser_id 在整个 View 中可用。您可以像 self.kwargs.get('pk')self.request.user.pk 一样使用它们。请检查下面的代码以了解实现细节。

class PostView(APIView):
permission_classes = (IsAuthenticated,)

def get_object(self):
pk = self.kwargs.get('pk')
user_id = self.request.id
try:
return Post.objects.get(pk=pk,user_id=user_id)
except Post.DoesNotExist:
raise Http404

def get(self,request, *args, **kwargs):
# ...
pass

def put(self, request, *args, **kwargs):
# ...
pass

def post(self,request, *args, **kwargs):
# ...
pass

关于python - Django 1.11 get() 缺少 1 个必需的位置参数 : 'pk' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54345563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com