[Fixed]-Converting Boolean value from Javascript to Django?

6👍

Try this.

from django.utils import simplejson

def post(self, request, *args, **kwargs):
    isUpvote = simplejson.loads(request.POST.get('isUpvote'))

15👍

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
👤Zippp

4👍

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 🙂

4👍

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.

👤SaeX

1👍

Javascript way of converting to a Boolean is

//Your variable is the one you want to convert
var myBool = Boolean(yourVariable); 

However in your above code you seem to be passing a string instead of the variable here

isUpvote = request.POST.get('isUpvote')

Are you sure you are doing it correctly ?

1👍

With Python’s ternary operator:

isUpvote = True if request.POST.get("isUpvote") == "true" else False

Also I should mention that if you are working with Django’s forms and are trying to pass compatible Boolean value to the Form or ModelForm class via Ajax, you need to use the precise values Django is expecting.

Assuming null=True on your model:

  1. Unknown
  2. Yes (True)
  3. No (False)

So for example, the following would deliver Boolean data to Django’s form properly:

<input type="radio" id="radio1" name="response" value="2">
<label for="radio1">Yes</label>
<input type="radio" id="radio2" name="response" value="3">
<label for="radio2">No</label>

1👍

Since Django 1.5 dropped support for Python 2.5, django.utils.simplejson is no longer part of Django as you can use Python’s built in json instead, which has the same API:

import json

def view_function(request):
    json_boolean_to_python_boolean = json.loads(request.POST.get('json_field'))

1👍

I have faced the same issue when calling django rest api from js, resolved it this way:

isUpvote = request.POST.get("isUpvote")
isUpvote = isUpvote == True or isUpvote == "true" or isUpvote == "True"

1👍

Another alternative is to use literal_eval() from ast(Abstract Syntax Tree) library.

In Javascript/jquery:

$.ajax({
    url: <!-- url for your view -->,
    type: "POST",
    data: {
        is_enabled: $("#id_enable_feature").prop("checked").toString() <!-- Here it's either true or false> 
    }
})

In your Django view,

from ast import literal_eval

def example_view(request):
    is_enabled = literal_eval((request.POST.get('is_enabled')).capitalize())
    print(is_enabled)    # Here, you can check the boolean value in python like True or False

0👍

I usually convert JavaScript Boolean value into number.

var xhr = {
    'isUpvote': Number(isUpvote)
};

In python:

try:
  is_upvote = bool(int(request.POST.get('isUpvote', 0)))
except ValueError:
  // handle exception here

0👍

You can pass the strings “true” or “false” to boolean only with

isUpvote = request.POST.get('isUpvote') == 'true'

Leave a comment