Why delete option not coming in the http://127.0.0.1:8000/store/products when we override Destroy method.
Please assist ASAP. I am using the same code which Mosh is using in Django., I am in Routers Video of Django_Part 2.
Why delete option not coming in the http://127.0.0.1:8000/store/products when we override Destroy method.
Please assist ASAP. I am using the same code which Mosh is using in Django., I am in Routers Video of Django_Part 2.
Remove the delete method completely and for destroy method write the following code:
def destroy(self, request, *args, **kwargs):
if OrderItem.objects.filter(product_id=kwargs['pk']).count() > 0:
return Response({'error': 'Product cannot be deleted as it is associated with an order item.'},
status=status.HTTP_405_METHOD_NOT_ALLOWED)
return super().destroy(request, *args, **kwargs)
This may help
So, my query here is why implementing the def destroy method removes the Delete
class ProductViewSet(ModelViewSet):
queryset = Product.objects.select_related('collection').all()
serializer_class = ProductSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ['collection_id']
def get_serializer_context(self):
return {'request':self.request}
def destroy(self, request,*args , **kwargs):
if OrderItem.object.filter(product_id=kwargs['pk']).count() > 0:
return Response({'error': 'Product cannot be deleted because it is associated with an order item.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
return super().destroy(request,*args,**kwargs)
while, keeping the “def delete” method retain the Delete button from product-list.
def delete(self,request,pk):
product = get_object_or_404(Product, pk=pk)
if product.orderitems.count() > 0:
return Response({'error': 'Product cannot be deleted because it is associated with an order item.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
product.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Why having the “def destroy” enables the Delete button in only Product list not in Product Detail, this is my query. please assist