Converting Boolean value from Javascript to Django?
ajax, django, javascript, jquery, python
Solution
Try this.
from django.utils import simplejson
def post(self, request, *args, **kwargs):
isUpvote = simplejson.loads(request.POST.get('isUpvote'))
Problem
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....