3
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')
2
Try to encode the image using base64.b64encode()
instead of the base64.b64decode()
method.
encoded_image = base64.b64encode(image.read())
Also, send json encoded data with content type set to application/json
.
self.client.post(url, json.dumps(data), content_type='application/json')
- [Django]-Specifying Django Query Filters at Run Time
- [Django]-Error in django interactive shell on pydev eclipse
2
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.
- [Django]-Django: ImportError: No module named sslserver
- [Django]-Django – Exception Value: Unexpected end of expression in if tag
- [Django]-Django admin StackedInline in custom tab
- [Django]-What's your favorite way to test the javascript in your djangoapp?
1
You have to set the format
of client
to JSON
:
response = self.client.post(url, data, format='json')