15

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

3
  • Are you sure you are doing a correct request ? Check answer below
    – woofmeow
    Commented Aug 12, 2013 at 2:01
  • There are only strings in url encoded form data, you could use json to transport boolean data. Or you could check if isUpvote is the string "true"(or "false") and set the appropriate value.
    – Musa
    Commented Aug 12, 2013 at 2:02
  • 1
    @user2492270, if isUpvote is saved as a string (as opposed to a Boolean), I would think then that Python would treat it as "not empty" (hence True), even if the string was "false".
    – wasabigeek
    Commented Jan 1, 2015 at 17:09

11 Answers 11

16

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
6

Try this.

from django.utils import simplejson

def post(self, request, *args, **kwargs):
    isUpvote = simplejson.loads(request.POST.get('isUpvote'))
1
  • In Django 1.5 and above you should use native Python module json instead, see my answer below. Commented May 3, 2018 at 8:58
5

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.

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 ?

2
  • Thanks for the response!! I added some additional information to my question :( still haven't figured out what is wrong Commented Aug 12, 2013 at 2:10
  • @user2492270 check these 2 lines isUpvote = request.POST.get('isUpvote') and vote, created = Vote.objects.get_or_create(user_voted=user_voted) . I think you are treating isUpvote as a string when sending the request. Im not sure if thats the way its done in django. Also rememeber that you are sending an object xhr in your request. Try looking online at how to access object properties. Thats as much I can do ... feel free to accept the answer if it helps.
    – woofmeow
    Commented Aug 12, 2013 at 2:17
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

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
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
  • I recommend you add text toi explain why this is the solution. If I understand things correctly, this could be a good answer to the question, but without explanation accompanying it, and why it is better than other answers already posted, it is likely to get deleted.
    – joanis
    Commented Aug 8, 2019 at 15:22
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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.