[英]Django Rest Framework - Why am I getting an error when the function isn't even supposed to do anything
Have this URL:有这个 URL:
path("products/product/<int:product>/rating/", ProductRating.as_view()),
and this view to handle the URL:这个视图处理 URL:
class ProductRating(APIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = ProductRatingSerializer
def get(self, request):
breakpoint()
In the URL the product in int:product is just the id of the product in question.在 URL 中,int:product 中的产品只是相关产品的 ID。 No matter what I put there whether it be int:pk or int:id I get the same error every time:
无论我放在那里是 int:pk 还是 int:id 我每次都会得到同样的错误:
TypeError: get() got an unexpected keyword argument 'product'
I have tried using generic view RetrieveAPIView and just an APIView and i get the same error.我试过使用通用视图 RetrieveAPIView 和一个 APIView,我得到了同样的错误。 Why am I getting an error and not the breakpoint?
为什么我收到错误而不是断点?
def get(request, request, product):
breakpoint()
it should work now !它现在应该工作了!
Whenever you deal with a url that have a query parameter(id, pk, slug...) in the path its going to passed to view function as kwarg.每当你处理一个 url 时,它的路径中有一个查询参数(id,pk,slug ...),它会传递给将 function 视为 kwarg。 so you have either define explicit argument that captures that or u can defined a **kwargs argument in the function.
所以你要么定义捕获那个的显式参数,要么你可以在 function 中定义一个 **kwargs 参数。
the implementation:实施:
def get(self, request, product):
....
or或者
def get(self, request, **kwargs):
product = kwargs.get("product")
...
Improved with explanation:改进说明:
Firstly adjust your url as following:首先调整你的 url 如下:
path("products/rating/<int:product>",ProductRating.as_view()),
It is to avoid any possible conflicts with other urls, to put the keyword at the end.为避免与其他网址发生任何可能的冲突,将关键字放在最后。 Also add *args and **kwargs with your get function to pass the sent keyword to the function.From the error in extracting the product, it seems this will resolve your issue.
还要在 get function 中添加 *args 和 **kwargs 以将发送的关键字传递给 function。从提取产品的错误来看,这似乎可以解决您的问题。
Below i have improvised the get function, so that you can extract the url parameter for the class based view, by using self.kwargs, and also return JsonResponse as to complete the function to return a response.下面我即兴创作了 get function,这样你就可以通过使用 self.kwargs 为基于 class 的视图提取 url 参数,并返回 JsonResponse 作为完成 function 返回响应。
from django.http import JsonResponse
class ProductRating(APIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = ProductRatingSerializer
def get(self, request, *args, **kwargs):
product_id = self.kwargs["product"]
breakpoint()
return JsonResponse(data={"status": "200, Yay it works"})
code like below dear代码如下亲爱的
class ProductRating(APIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = ProductRatingSerializer
def get(request, request, format=None):
breakpoint()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.