I'm using the DRF test api for testing my serializers, for instance I made my data like this:
image_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../media/', 'product_images/', 'myimage.png')
with open(image_path) as image:
encoded_image = base64.b64decode(image.read())
data = {
u'small_name': u'Product Test Case Small Name',
u'large_name': u'Product Test Case Large Name',
u'description': u'Product Test Case Description',
u'images': [
{u'image': encoded_image}
],
u'variants': [
{u'value': u'123456789'}
]
}
response = self.client.post(url, data, 'multipart')
However when I receive the data on the respective serializer the variants array and the images array are empty.
What could be the issue here?
Thanks to Linovia and Rahul Gupta I was able to resolve the image and arrays problem. I changed my serializer to receive an Base64ImageField using the one provided by django-extra-fields. Rahul also pointed a silly error on my code.
I'll leave some code to help someone with the same problem.
serializers.py file
from drf_extra_fields.fields import Base64ImageField
class ProductImageSerializer(serializers.ModelSerializer):
source = Base64ImageField(source='image', required=False, )
test.py file
image_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../media/', 'product_images/', 'myimage.png')
with open(image_path) as image:
encoded_image = base64.b64encode(image.read())
data = {
u'small_name': u'Product Test Case Small Name',
u'large_name': u'Product Test Case Large Name',
u'description': u'Product Test Case Description',
u'images': [
{u'source': encoded_image}
],
u'variants': [
{u'value': u'123456789'}
]
}
response = self.client.post(url, data, format='json')
You can not have both the image upload and nested data. Either you want to upload the image and use multipart encoding (HTML forms) which means your arrays will not work (unless it's a list of foreign key or similar). This could work with JSon content type but then you'll loose the ability to upload image. Your option there might be to encode with base64 the image and upload it but you'll have to customize a few things on the serializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With