Converting Boolean value from Javascript to Django?
probably it could be better to have 'isUpvote' value as string 'true' or 'false' and use json to distinguish its boolean value
import json
isUpvote = json.loads(request.POST.get('isUpvote', 'false')) # python boolean
I encounter the same problem and I solved the problem with more clear way.
Problem:
If I send below JSON to server, boolean fields come as test("true", "false") and I must be access to catalogues
as request.POST.getlist("catalogues[]")
. Also I can't make form validation easly.
var data = {
"name": "foo",
"catalogues": [1,2,3],
"is_active": false
}
$.post(url, data, doSomething);
Django request handler:
def post(self, request, **kwargs):
catalogues = request.POST.getlist('catalogues[]') # this is not so good
is_active = json.loads(request.POST.get('is_active')) # this is not too
Solution
I get rid of this problems by sending json data as string and converting data to back to json at server side.
var reqData = JSON.stringify({"data": data}) // Converting to string
$.post(url, reqData, doSomething);
Django request handler:
def post(self, request, **kwargs):
data = json.loads(request.POST.get('data')) # Load from string
catalogues = data['catalogues']
is_active = data['is_active']
Now I can made form validation and code is more clean :)
I came accross the same issue (true/false by Javascript - True/False needed by Python), but have fixed it using a small function:
def convert_trueTrue_falseFalse(input):
if input.lower() == 'false':
return False
elif input.lower() == 'true':
return True
else:
raise ValueError("...")
It might be useful to someone.
Try this.
from django.utils import simplejson
def post(self, request, *args, **kwargs):
isUpvote = simplejson.loads(request.POST.get('isUpvote'))