I’m encountering a MultiValueDictKeyError
in my Django project when trying to access the API at http://127.0.0.1:8000/api/products/
. The error occurs on this line: category = self.request.GET['category']
.
Here is my view:
class ProductList(generics.ListCreateAPIView):
queryset = models.Product.objects.all()
serializer_class = serializers.ProductListSerializer
def get_queryset(self):
qs = super().get_queryset()
category = self.request.GET['category']
category = models.Product.objects.get(category)
qs = qs.filter(category=category)
return qs
My Product
model is defined as follows:
class Product(models.Model):
category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, related_name='product_in_category')
retailer = models.ForeignKey(Retailer, on_delete=models.SET_NULL, null=True)
title = models.CharField(max_length=200)
detail = models.CharField(max_length=200, null=True)
price = models.FloatField()
def __str__(self) -> str:
return self.title
Here is my serializer:
class ProductListSerializer(serializers.ModelSerializer):
productreview = serializers.StringRelatedField(many=True, read_only=True)
class Meta:
model = models.Product
fields = ['id', 'category', 'retailer', 'title', 'detail', 'price', 'productreview']
def __init__(self, *args, **kwargs):
super(ProductListSerializer, self).__init__(*args, **kwargs)
I am trying to call a list of products according to the product category from my React frontend, but I keep encountering the MultiValueDictKeyError
. I tried using GET.get
and various other approaches but haven’t been able to resolve the issue.
Here is the error traceback:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/products/
Django Version: 4.2.13
Exception Type: MultiValueDictKeyError
Exception Value: 'category'
How can I fix this error and properly filter the products by category?
Shital is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.