Get value in a post request, Django - django

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.

Related

Get max and min formatted date values from queryset in Django

I have a one to many relation between session and camp. Now I have to get the max and min dates of all camps combined for a particular session.
I am able to do it like this:
sess = Session.objects.last()
max_min_dates = sess.camp.aggregate(Min('start_date'), Max('end_date'))
But if I try to send this from HttpResponse then I am getting this error:
TypeError: Object of type 'date' is not JSON serializable
So I need to send the formatted date values in that. How can I modify the above code to get the same?
The default encoder for json.dumps() does not support date encoding (ie. can't convert date into str). You can use django encoder instead, it supports a few more data types see the link for more info.
Django Ref
import json
from django.core.serializers.json import DjangoJSONEncoder
json_str = json.dumps(max_min_dates, cls=DjangoJSONEncoder)

How to send multiplechoicesfield in post request - Postman

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?

How to send JSON data with form data using Flask

I'm making a system to track entries to a sports day event and I can get the data from the form to the Python back-end but I don't know how to get the data for the event entries to the back-end too.
I have a form I've already created using Flask and WTForms and I can submit all the data relating to the user but since they can enter from just a single event all the way up to every event they are able to enter the form will have a variable number of selection fields, I want to pack this data from the selection fields into a JSON string and then have Python process it since that is very easy. My only problem is, how can I get this data into a JSON string then send it in a single request to the back-end with the other data, like first name, last name etc.
Screenshot showing the user interface of the form
from flask import jsonify
#app.route('/selects')
def selects():
selects = ['one', 'two']
return jsonify(selects)
I have the same question and found answer in this tutorial. If you already use WTForm to make the form, the content can be access via methods. This should be straightforward. https://pythonspot.com/category/pro/web/page/2/

Ionic To Django POST data auto name change

Hi I am building an application in which my Ionic App need to send a post message to Django Backend.
My data at Ionic end during pos seem to be like this
// This is the value from ion-select with multiple set true
let data = {'selectedId':[1,2,3,4,5,6]}
In my django request.POST the data is converted like this
<QueryDict : {u'selectedId[]' : [u'1',u'2',u'3',u'4',u'5']}>
Why does the key value automatically converted from "selectedId" in Ionic to "selectedId[]"
if i try to get the array value in Django by performing
request.POST['selectedId[]'] this give me the length of the array 5
request.POST['selectedId'] this give me a MultiValueDictKeyError
The behavior you are seeing is because you are posting the values to you django endpoint as form-encoded values. When you post non-file values that are form-encoded, they are always posted as strings. If you want to preserve the type of the input you are passing in, you should use a JSON post instead of a form post.

Converting JSON to model instance in Django

What's the best way in django to update a model instance given a json representation of that model instance.
Is using deserialize the correct approach? Are there tutorials available out there?
The best approach would be to utilize one of the existing Django applications that support serializing model instances to and from JSON.
In either case, if you parse the JSON object to a Python dictionary, you can basically use the QuerySet.update() method directly.
So, say you get a dictionary where all the keys map to model attributes and they represent the values you'd want to update, you could do this:
updates = { # Our parsed JSON data
'pk': 1337,
'foo': 'bar',
'baz': 192.05
}
id = updates.pop('pk') # Extract the instance's ID
Foo.objects.filter(id=id).update(**updates) # Update the instance's data