I noticed that when Boolean data is sent from javascript to Django view, it is passed as "true"/"false" (lowercase) instead of "True"/"False"(uppercase). This causes an unexpected behavior in my application. For example:
vote.js
....
var xhr = {
'isUpvote': isUpvote
};
$.post(location.href, xhr, function(data) {
doSomething()
});
return false;
});
views.py
def post(self, request, *args, **kwargs):
isUpvote = request.POST.get('isUpvote')
vote, created = Vote.objects.get_or_create(user_voted=user_voted)
vote.isUp = isUpvote
vote.save()
when I save this vote and check my Django admin page, "isUpvote" is ALWAYS set to True whether true or false is passed from javascript. So what is the best way to convert javascript's "true/false" boolean value to Django's "True/False" value???
Thanks!!
ADDED:::::
Well, I added some 'print' lines to check whether I was doing something wrong in my view:
print(vote.isUp)
vote.isUp = isUpvote
print(vote.isUp)
vote.save()
The result:
True
false //lowercase
And then when I check my Django admin, it is saved as "True"!!! So I guess this means lowercaes "false" is saved as Django "True" value for some weird reason....
I encounter the same problem and I solved the problem with more clear way.
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
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 :)
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
Try this.
from django.utils import simplejson
def post(self, request, *args, **kwargs):
isUpvote = simplejson.loads(request.POST.get('isUpvote'))
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.
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