How to pass a boolean from javascript to python?

In your Python code do this:

active = True if request.POST.get('active') == 'true' else False

Or even simpler:

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

Be aware that the get() function will always return a string, so you need to convert it according to the actual type that you need.


The answer by Oscar is a 1-liner and I'd like to take nothing from it but, comparing strings is not the cleanest way to do this.

I like to use the simplejson library. Specifically loads parses the natural json form of JavaScript to native Python types. So this technique can be used for a wider set of cases.

This will give you uniform code techniques which are easier to read, understand & maintain.

From the docs:

Deserialize s (a str or unicode instance containing a JSON document) to a Python object.

import simplejson as sjson
valid_python_var = sjson.loads(json_str_to_parse)

Or in the likely scenario that you are receiving it via parameter passing:

var_to_parse = request.POST.get('name_of_url_variable') #get url param
    if var_to_parse is not None: #check if param was passed, not required
        parsed_var = sjson.loads(var_to_parse) # loads does the work

Note: Import libraries using common sense, if you are going to use them once there is no need for it.


Assuming that you could send boolean value to the server as true/false or 1/0, on the server-side you can check both cases with in:

def warning_message(request):
    active = request.POST.get('active') in ['true', '1']
    print active
    return HttpResponse()

Otherwise, if you are sure that your boolean will be only true/false use:

def warning_message(request):
    active = request.POST.get('active') == 'true'
    print active
    return HttpResponse()