Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Boolean value from Javascript to Django?

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....

like image 275
user2492270 Avatar asked Aug 12 '13 01:08

user2492270


4 Answers

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 :)

like image 80
Mesut Tasci Avatar answered Nov 18 '22 10:11

Mesut Tasci


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
like image 43
Zippp Avatar answered Nov 18 '22 09:11

Zippp


Try this.

from django.utils import simplejson

def post(self, request, *args, **kwargs):
    isUpvote = simplejson.loads(request.POST.get('isUpvote'))
like image 6
Conor Patrick Avatar answered Nov 18 '22 11:11

Conor Patrick


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.

like image 4
SaeX Avatar answered Nov 18 '22 11:11

SaeX