I have a model for random Products which has an image field and a default image. I want to make it such that the client doesn’t have to send an image when creating a new product through the API (using DRF). Below are the model, serializer and view
# Model
...
total_stock = models.PositiveIntegerField(default=0)
product_image = models.ImageField(upload_to='images', blank=True, default="/static/images/default_product.png")
# Serializer
class ProductSerializer(serializers.ModelSerializer):
product_image = serializers.ImageField(max_length=None, allow_empty_file=False)
class Meta:
model = Product
fields = [
'total_stock', 'product_image'...
]
# View
class ProductCreate(generics.CreateAPIView):
permission_classes = [IsAuthenticated]
queryset = Product.objects.all()
serializer = ProductSerializer()
In order for the view to accept a payload without an image, I have to modify the serializer like this:
class ProductSerializer(serializers.ModelSerializer):
product_image = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) # added "required=False"
But when I do that, I get the error:
The response content must be rendered before it can be iterated over.
Request Method: GET
Request URL: http://127.0.0.1:8000/product/create/
Django Version: 4.0.5
Exception Type: ContentNotRenderedError
Exception Value:
The response content must be rendered before it can be iterated over.
Exception Location: .../lib/python3.10/site-packages/django/template/response.py, line 127, in __iter__
Python Executable: /.../bin/python
Python Version: 3.10.4
...
All the other questions I have investigated are with respect to queries but I’m not making a query here.