我尝试使用(非api-服务器端)代码创建一个添加到购物车的api到Django rest框架. 但当我调用邮差中的api时它显示403 forbidden。我没有在这个视图中使用任何序列化器。
另外,我尝试使用APIView和序列化器,它不起作用。我是新的django rest框架。我需要帮忙写这篇文章。
我的模型:
class OrderItem(models.Model) :
user = models.ForeignKey(User,on_delete=models.CASCADE,null=True, blank=True)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.item.name}"
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True)
items = models.ManyToManyField(OrderItem,blank=True, null=True)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.email
我的观点:
@login_required
def add_to_cart(self, pk):
item = get_object_or_404(Product, pk=pk)
order_item, created = OrderItem.objects.get_or_create(
item=item,
user=self.request.user,
ordered=False
)
order_qs = Order.objects.filter(user=self.request.user, ordered=False)
if order_qs.exists():
order = order_qs[0]
if order.items.filter(item__pk=item.pk).exists():
order_item.quantity += 1
order_item.save()
return Response({"message": "Added quantity Item", },
status=status.HTTP_200_OK
)
else:
order.items.add(order_item)
return Response({"message": " Item added to your cart", },
status=status.HTTP_200_OK,
)
else:
ordered_date = datetime.timezone.now()
order = Order.objects.create(user=self.request.user, ordered_date=ordered_date)
order.items.add(order_item)
return Response({"message": "Item added to your cart", },
status=status.HTTP_200_OK,
)
我的网址:
路径(api/addorderitem int: pk,观点。add_to_cart name = ' api-addorder '),
下面的代码使用APIView:
class AddtoOrderItemView(ListCreateAPIView):
permission_classes = [IsAuthenticated]
queryset = OrderItem.objects.all()
serializer_class = OrderItemSerializer
def post(self,request,*args,**kwargs)
"""same code as abvoe""
这里的post函数不接受pk,但我有pk在我的代码是无法识别的。所以,我不知道该怎么做,因为我们不能使用def add_to_cart(self, pk)在ListCreateAPIView.
我的序列化器:
class OrderItemSerializer(serializers.ModelSerializer):
class Meta:
model = OrderItem
fields = ['id','user','ordered','item', 'quantity']
depth = 1
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
您可能因为请求用户未经身份验证而获得403禁止。由于您使用的是@login_required
装饰器,因此只有经过身份验证的用户才能访问add_to_cart视图。
要访问ListCreateAPIView中的pk,请尝试
pk = self.kwargs.get('pk')
最后,我可以使用APIView向购物车添加商品. APIView是一个基类,我们可以根据需要和业务逻辑重写任何自定义函数(post, get等)。
这是我的观点,这是有效的。
class AddtoOrderItemView(APIView):
permission_classes = [IsAuthenticated]
# queryset = OrderItem.objects.all()
# serializer_class = OrderItemSerializer
# @action(detail=True, methods=['post'])
# @login_required
def post(self, request, pk):
item = get_object_or_404(Product, pk=pk)
order_item, created = OrderItem.objects.get_or_create(
item=item,
user=self.request.user,
ordered=False
)
order_qs = Order.objects.filter(user=self.request.user, ordered=False)
if order_qs.exists():
order = order_qs[0]
if order.items.filter(item__pk=item.pk).exists():
order_item.quantity += 1
order_item.save()
return Response({"message": "Quantity is added",
},
status=status.HTTP_200_OK
)
else:
order.items.add(order_item)
return Response({"message": " Item added to your cart", },
status=status.HTTP_200_OK,
)
else:
ordered_date = datetime.now()
order = Order.objects.create(user=self.request.user, ordered_date=ordered_date)
order.items.add(order_item)
return Response({"message": "Order is created & Item added to your cart", },
status=status.HTTP_200_OK,
)
这里我重写post函数,使用(self,request,pk)作为所需的参数。这不是重写post函数的标准方式,但我们可以在APIView中这样写。