Assume I have some data as below,
{
"name":"John",
"age":30,
"cars":
{
"car_img_1":"car_img_file1",
"car_img_2":"car_img_file2",
"car_img_3":"car_img_file3"
}
}
How can I send it using POSTMAN with form-data?
NOTES
1. car_img_fileX will be the file(.jpg,.png etc types)
2. What I'd tried -->> POSTMAN Screenshot.
3. Local server builted with Django framework
Current Output
Receiving 5 different items/data instaed of Nested data--> see this Pycharm Debugger Output
Try this:
cars[0][car_img_1]:car_img_file1
cars[1][car_img_2]:car_img_file2
You can insert it in "bulk-edit" mode.
I found this answer from this problem. Edited as per your code.
Convert your Image Fields to base64Image and send it through the JSON data.
All you need to do is:
go to https://www.base64-image.de/ and convert the image to base64 format. Copy the encoded result.
Install django-extra-fields package in your project from here
In your serializer_class, import and change the image field to Base64ImageField:
serializers.py
...
from drf_extra_fields.fields import Base64ImageField
...
Now, go to your postman and send the JSON data like the following. Remember to send that encoded image in your image field in JSON.
{
"name":"John",
"age":30,
"cars":
{
"car_img_1":"<base64 encoded image>",
"car_img_2":"<base64 encoded image>",
"car_img_3":"<base64 encoded image>"
}
}
Related
I use django-multiselectfield package in my project and based on its docs I use MultipleChoiceField in my serializer:
class InsCatSerializer(serializers.ModelSerializer):
levels = fields.MultipleChoiceField(choices=LEVEL)
when I send a request with raw JSON in postman that works fine
"levels": ["INTERMEDIATE", "ADVANCED"]
But I need to use form data because I have files and images in my request!
I try this way:
levels:INTERMEDIATE
levels:ADVANCED
but just saved the last element ( ADVANCED in this example )
any suggestion to solve?
Json Array and Form data can't work together. Please stringify your array or don't use form data at all.
Read more: JS, how to append array in FormData?
When I POST my form, I receive the following exception:
act_date: ["Date has wrong format. Use one of these formats instead: YYYY-MM-DD."]
And the same validation error for other DateFields.
I changed the default date format in extjs (Ext.util.Format.defaultDateFormat= 'Y-m-d') which did not work.
So next I define date format in Django setting:
'DATE_FORMATS': [("%Y-%m-%d"),],
This also hasn't worked.
When you said I changed the default date format in extjs (Ext.util.Format.defaultDateFormat= 'Y-m-d') which did not work. it's the date format don't work or again you'r server validation ?
Cause actually if i do this :
var d = new Date();
Ext.Date.format(d, 'Y-m-d');
That give me : "2019-03-05" and it's seem to be correct.
Have you check inside of you'r POST request the format of the sending date ?
You maybe have a unexpected date format before sending you'r request.
I would like some help about my code. My goal is to send at the same time string variables as a ini plain text and a bmp file in an httpResponse.
For the moment I insert the decoded bytes of the bmp file in an ini parameter, take into account that I communicate with an interphone which is only client but not server so I can only make httpresponses but no requests.
If I base64 encode my image, I'll need to change the software of our interphone to decode it, for the moment I can't, can you tell me if base64 encode bytes is mandatory in my case ?
I made some researches on the web and I saw that people base64 encode their images or they make multipart response.
Could you help me to implement a multipart response please, even hand made, that would interest me ?
I show you how I do for the moment, I put the image in the "string" ini parameter:
def send_bmp():
outputConfig = io.StringIO()
outputConfig.write('[RETURN_INFO]\r\n')
outputConfig.write('config_id=255\r\n')
outputConfig.write('config_type=2\r\n')
outputConfig.write('action=3\r\n')
outputConfig.write('[DATABASE]\r\n')
file = open(django_settings.TMP_DIR+'/qrcode.bmp', 'rb').read()
outputConfig.write('size_all='+str(len(file))+'\r\n')
outputConfig.write('string='+file.decode('iso-8859-1')+'\r\n')
outputConfig.write('csum='+str(sum(file))+'\r\n')
body = outputConfig.getvalue()
httpR = HttpResponse(body, content_type='text/plain;charset=iso-8859-1')
httpR['Content-Length'] = len(body)
return httpR
Here is the response I get :
https://gist.github.com/Ezekiah/e6fd50f13c05f338f27a
If you need to mix the image file content with the rest of the response I think you have to use Base64 encoding. If it is possible to return the ini parameters in one request and the file in another Django provides a FileResponse class(subclass of StreamingHttpResponse) that you can use to return the bmp file in chunks, like this:
from django.http import FileResponse
def send_bmp(request):
file = open(django_settings.TMP_DIR+'/qrcode.bmp', 'rb')
return FileResponse(file)
am getting the following post data in my django app
POST
Variable Value
csrfmiddlewaretoken u'LHM3nkrrrrrrrrrrrrrrrrrrrrrrrrrdd'
id u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null'
am trying to get the id value in variable id i.e "id":4 (the value 4). When I do request.POST.get('id')I get the whole json string. u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null' How can I get the "id" in the string?
The data you are sending is simply a json string.
You have to parse that string before you can access data within it. For this you can use Python's json module (it should be available if you're using Python 2.7).
import json
data = json.loads( request.POST.get('id') )
id = data["id"]
If you somehow don't have the json module, you can get the simplejson module.
For more details, refer this question : best way to deal with JSON in django
That's happening because id is string, not dict as it should be. Please provide your template and view code to find source of problem.
On my server the array appears as follows:
data = [u'Data1', u'Data2', u'Data3']
In Django, I send the data through to the client using:
render(..., {'data': data})
On the client side I try to render in JavaScript using:
{{data}}
and get:
[u'Data1B', u'Data2', u'Data3']
How can I fix this encoding issue?
You need to safe escape the string inorder to work fine
{{data|safe|escape}}
You can also pass your data as a json object. In your view.py
from django.utils import simplejson
...
render(...{'data':simplejson.dumps(data)})
and then in your javascript function
var data = JSON.parse({{data}})
But as #karthikr already said, |safe is your case absolutely sufficient.